当用户滚动页面时,如何让div元素在页面上下移动? (该元素始终可见)
答案 0 :(得分:69)
您希望将fixed属性应用于元素的位置样式。
position: fixed;
您使用的浏览器是什么?并非所有浏览器都支持固定属性。阅读更多关于谁支持它,谁不支持和一些解决方案
http://webreflection.blogspot.com/2009/09/css-position-fixed-solution.html
答案 1 :(得分:59)
只是为了一个更动画和可爱的解决方案:
$(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"});
});
答案 2 :(得分:11)
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");
}
答案 3 :(得分:5)
这是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);
});
});
答案 4 :(得分:4)
只需在div样式中添加position: fixed;
。
我已经检查过,并且我的代码工作正常。
答案 5 :(得分:3)
你可能想查看Remy Sharp的recent article on fixed floating elements at jQuery for Designers,它有一个很好的视频和关于如何在客户端脚本中应用此效果的文章