简体   繁体   English

当我滚动页面时,如何使<div>上下移动?

[英]How do I make a <div> move up and down when I'm scrolling the page?

How can I make a div element move up and down the page when the user is scrolling the page? 当用户滚动页面时,如何让div元素在页面上下移动? (where that element is always visible) (该元素始终可见)

You want to apply the fixed property to the position style of the element. 您希望将fixed属性应用于元素的位置样式。

position: fixed;

What browser are you working with? 你在用什么浏览器? Not all browsers support the fixed property. 并非所有浏览器都支持固定属性。 Read more about who supports it, who doesn't and some work around here 详细了解谁支持它,谁不支持,有些人在这里工作

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

Just for a more animated and cute solution: 只是为了一个更动画和可爱的解决方案:

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

And a pen for those who want to see: http://codepen.io/think123/full/mAxlb , and fork: http://codepen.io/think123/pen/mAxlb 对于那些想看的人来说: http//codepen.io/think123/full/mAxlb和fork: http//codepen.io/think123/pen/mAxlb

Update: and a non-animated jQuery solution: 更新:和一个非动画的jQuery解决方案:

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

using position:fixed alone is just fine when you don't have a header or logo at the top of your page. 使用position:fixed当你的页面顶部没有标题或徽标时,单独position:fixed就可以了。 This solution will take into account the how far the window has scrolled, and moves the div when you scrolled past your header. 此解决方案将考虑窗口滚动的距离,并在滚动浏览标题时移动div。 It will then lock it back into place when you get to the top again. 当你再次到达顶部时,它会将其锁定回原位。

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");
}

Here is the Jquery Code 这是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);
        });
    });

Just add position: fixed; 只需添加position: fixed; in your div style. 在你的div风格。

I have checked and Its working fine in my code. 我已经检查过它在我的代码中工作正常。

你可能想看看Remy Sharp 最近关于jQuery for Designers的固定浮动元素的文章 ,它有一个很好的视频和关于如何在客户端脚本中应用这个效果的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM