如何在滚动时将此元素固定在页面顶部?

时间:2013-04-29 18:44:55

标签: html css search scroll

我正在为我的UI设计类开发一个项目,需要帮助在滚动时将元素修复到页面顶部。

以下是我到目前为止的内容:http://ieatthings.com/opinio/query.html

滚动时,搜索栏应向上移动,越过导航栏,并且非常适合放置到位置,让用户在页面中间进行搜索。但问题是搜索栏不断上升!

我使用了本教程中的Javascript:Fix object to top of browser window when scrolling。我已经尝试了各种各样的可能性和组合,但遗憾的是没有让这个该死的东西工作。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

与页面滚动的距离相比,您必须使用Javascript来测试页面上元素(“myElement”)的位置。如果页面已向上滚动超出元素,则更改元素的css以将其捕捉到页面顶部。注意:移动浏览器不喜欢“position:fixed;”风格属性。

为您的元素指定“myElement”的ID,并将其插入您的代码中。

<script type="text/javascript"> 

var yPosition; // save original y position of element here

window.onload = function(){ // once entire page is loaded this function is fired
    // save original y position of element before it is scrolled
    yPosition = document.getElementById("myElement").offsetTop;
}

window.onscroll = function(){ // scrolling fires this function      

    var myElement = document.getElementById("myElement"); // for cleaner code

    // compare original y position of element to y position of page
    if( yPosition <= window.pageYOffset ){ 

        // snap element to the top by changing css values of element
        myElement.style.position = "fixed";
        myElement.style.top = "0px"; 

    }else{          

        // re-position to original flow of content
        myElement.style.position = "relative";
        myElement.style.top = ""; // set to default         
    }               
}      
</script>

希望这有帮助!

相关问题