javascript-滚动页面时如何使

上下移动?

当用户滚动页面时,如何使div元素在页面中上下移动? (该元素始终可见)

6个解决方案

72 votes

您想要将fixed属性应用于元素的位置样式。

position: fixed;

您正在使用什么浏览器? 并非所有浏览器都支持fixed属性。 了解更多有关谁支持它,谁不支持的信息以及此处的一些解决方法

[http://webreflection.blogspot.com/2009/09/css-position-fixed-solution.html]

Bob answered 2020-01-12T19:26:16Z

61 votes

只是为了获得更生动有趣的解决方案:

$(window).scroll(function(){

$("#div").stop().animate({"marginTop": ($(window).scrollTop()) + "px", "marginLeft":($(window).scrollLeft()) + "px"}, "slow" );

});

还有一支笔,供那些想看的人使用:[http://codepen.io/think123/full/mAxlb,]和叉子:[http://codepen.io/think123/pen/mAxlb]

更新:和非动画jQuery解决方案:

$(window).scroll(function(){

$("#div").css({"margin-top": ($(window).scrollTop()) + "px", "margin-left":($(window).scrollLeft()) + "px"});

});

11 votes

当页面顶部没有标题或徽标时,单独使用position:fixed很好。 该解决方案将考虑到窗口滚动了多远,并在滚动经过标题时移动了div。 然后,当您再次到达顶部时,它将重新锁定到位。

if($(window).scrollTop() > Height_of_Header){

//begin to scroll

$("#div").css("position","fixed");

$("#div").css("top",0);

}

else{

//lock it back into place

$("#div").css("position","relative");

}

lmno answered 2020-01-12T19:27:05Z

5 votes

这是jQuery代码

$(document).ready(function () {

var el = $('#Container');

var originalelpos = el.offset().top; // take it where it originally is on the page

//run on scroll

$(window).scroll(function () {

var el = $('#Container'); // important! (local)

var elpos = el.offset().top; // take current situation

var windowpos = $(window).scrollTop();

var finaldestination = windowpos + originalelpos;

el.stop().animate({ 'top': finaldestination }, 1000);

});

});

Alireza Masali answered 2020-01-12T19:27:25Z

4 votes

只需在您的div样式中添加position: fixed;即可。

我在代码中检查了它的运行状况。

chandrgupt answered 2020-01-12T19:27:49Z

3 votes

您可能想查看雷米·夏普(Remy Sharp)在jQuery for Designers上有关固定浮点元素的最新文章,其中有一段不错的视频和有关如何在客户端脚本中应用此效果的文章

Russ Cam answered 2020-01-12T19:28:09Z

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐