【问题标题】:JS get scroll instance heightJS获取滚动实例高度
【发布时间】:2015-09-06 08:48:31
【问题描述】:

我正在寻找一种方法来动态获取滚动位置高度实例,只要我滚动页面,同时更新 CSS。

我使用了这个 sn-p,但是 bodyHeight 的值在第一页加载时是固定的,在滚动和 CSS 时也不会更新。

var bodyHeight = $('body').scrollTop();
var fixedTop = bodyHeight - 50;//(50)topnav height
$('.fixed-inner').css('top', fixedTop + 'px');

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    试试类似的东西:

    <!DOCTYPE html>
    <html>
    <head>
        <style>
            div#main{
                background-color:green;
            }
        </style>
    </head>
    <body>
    <br /><br /><br /><br />
    <div id="main" style="height:300px; position:relative; overflow:scroll;">
        <div class="stairsImage" style="height:500px; width:300px; background-color:yellow; ">
           <h1 id="testName">Lorem Ipsum</h1>
        </div>
    </div>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js"></script> 
    
    <script>
    $(document).ready(function() {
    //-------------------------
       $(window).scroll(function(){
          var wScroll = $(this).scrollTop();
            console.log(wScroll);
    
          $("#testName").css({'transform' : 'translate(0px, '+ wScroll +'px)'});
    
       });  
    //-------------------------
       $("div#main").scroll(function(){
          var wScroll = $(this).scrollTop();
            console.log(wScroll);
    
          $("#testName").css({'transform' : 'translate(0px, '+ wScroll +'px)'});
    
       }) 
    });
    </script>       
    </body>
    </html>
    

    【讨论】:

    • 这很难,一切都乱七八糟。需要更多更好的方法!
    • 关注中间的片段://-------------------------
    【解决方案2】:

    试试这个

    var bodyHeight = $(window).scrollTop();
    var fixedTop = bodyHeight - 50;//(50)topnav height
    $('.fixed-inner').css('top', fixedTop + 'px');
    

    【讨论】:

    • 那是复制/粘贴。这里没有什么新鲜事。
    • 没有。在我的代码中是 $(window).scrollTop() 而不是 $('body').scrollTop()
    【解决方案3】:

    希望对你有帮助

    $(window).scroll(function () { 
        //You've scrolled this much:
           $('div').text("The scrool position is " + $ (window).scrollTop() + " pxs");
    });
    

    jsFiddle here

    祝你好运:)

    【讨论】:

      【解决方案4】:

      滚动页面时需要重新计算bodyHeight,并且有一个jquery事件,可以将bodyHeight作为全局变量。

      var bodyHeight = $('body').scrollTop();
      $(window).scroll(function () { 
          //recalculate the value every time the user scroll
          var bodyHeight = $(window).scrollTop();
          //doSomething()
      });
      

      进一步阅读:

      【讨论】:

        猜你喜欢
        • 2011-08-24
        • 2013-12-13
        • 2013-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-01
        相关资源
        最近更新 更多