使用jQuery在单击按钮上方添加内容时阻止页面移动

时间:2015-12-19 10:50:18

标签: javascript jquery scroll

我的页面上有三个部分,从上到下,A,B和C.您单击C部分中的按钮。现在,某些内容将加载到A部分(您单击的按钮上方),例如,内容使用jQuery的slideDown()方法。

现在,C部分向下滚动一点(因为新内容正在这样做)。这就是我想要阻止的。有没有办法让浏览器自动将页面滚动到与加载内容之前完全相同的位置?

2 个答案:

答案 0 :(得分:1)

如果你想确保按钮根本不在屏幕上移动,即使在其上方添加了内容,也应该这样做:

$("mybutton").click(function() {
    //Save the vertical position of the button before content is added.
    var x1 = $(this).offset().top;
    //Do whatever the button is suppose to do, including adding the new content.
    doAllTheStuff();
    //See how much we moved.
    var x2 = $(this).offset().top;
    var dx = x2 - x1;
    //Scroll the same amount to keep the button from moving on the screen.
    $(document).scrollTop($(document).scrollTop() + dx);
});

如果您在页面上使用此功能很多,您可能希望将代码更好地包装起来。这是一个有效的JSFiddle

这也可能是有趣的阅读:

答案 1 :(得分:0)

您在使用javascript:void(0);的锚标记中使用#in href属性,那么您的页面将不会滚动。

相关问题