CSS 动画移动页面 - 使用 CSS 修复当前元素上的页面滚动位置

css animation moves page - fix page scroll position on current element with css?

本文关键字:CSS 位置 元素 滚动 移动 动画 使用      更新时间:2023-09-26

给定以下简化问题:

foreach i in 1..100 do
    <div onclick="$("div").attr('class','expand');">block i</div>

而这个css:

div {
    height: 20px;
    transition: height 0.5s;
}
div.expand {
    height: 50px;
}

现在,当我单击一个div时,每个div都会得到"扩展"类。这意味着页面将展开。但是,一切都会向下滚动。这意味着如果我单击div 50,它可能不再出现在我的窗口中,我必须向下滚动才能再次看到它。

我很想让我点击的div 留在屏幕中央。这在CSS上是可能的,还是我需要JS?

有可能...你可以像这样使用 jQuery 的 .scrollTop() 方法:

$(window).scrollTop( $('.your_element').offset().top + $('.your_element').height() - $(window).height() );

此函数根据鼠标单击的位置滚动页面:

$(document).ready(function(){
    $('div').click(function(e){
        var offsetY = e.pageY -  $(window).scrollTop();
        $('div').attr('class','expand');
        $(window).scrollTop($(this).offset().top-offsetY);
    });
});

jsFiddle 上的示例