滚动元素而不使用硬编码值jQuery

时间:2016-10-21 16:59:53

标签: jquery css

对于工作,我必须在滚动时固定一个元素(例如,在页面上向下滚动将使元素自动调整以便随时可见)。我必须解决的问题是如何在没有硬编码高度值的情况下进行此操作。有没有办法做到这一点?

以下是代码:

// fix the orange box to the top after scrolling a certain amount
$(window).scroll(function(e){
     var scrollTop = $(window).scrollTop();

     // enforce a max based on current content length
     if ($(this).scrollTop() >= ($('.mainContent2ColLayout250').height() - 400))
         scrollTop = ($('.mainContent2ColLayout250').height() - 400);

     if ($(this).scrollTop() >= 340) 
         $('.fixedElement').css({'marginTop': scrollTop - 325, 'marginBottom': -1 * (scrollTop - 325)}); 

     if ($(this).scrollTop() < 340)
        $('.fixedElement').css({'marginTop': 0, 'marginBottom': 0}); 
});

任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:1)

应用

position: fixed

到那个元素

相关问题