How can I fix this element to stick at the top of the page on scroll?

£可爱£侵袭症+ 提交于 2019-12-24 23:25:33

问题


I'm working on a project for my UI design class and need help fixing an element to the top of a page on scroll.

Here's what I have so far: http://ieatthings.com/opinio/query.html

As you scroll, the search bar should move up, over the navbar, and fit nicely into place to let the user search while in the middle of a page. But the problem is that the search bar keeps going up!

I used the Javascript from this tutorial: Fix object to top of browser window when scrolling. I have tried all kinds of possibilities and combinations, but have unfortunately not gotten this damn thing to work.

Any suggestions?


回答1:


You will have to use Javascript to test the position of your element ("myElement") on the page compared to how far the page has been scrolled. If the page has been scrolled up beyond your element then you alter your element's css to snap it to the top of the page. Note: mobile browsers don't like the "position: fixed;" style property.

Give your element the id of "myElement" and insert this into your tag.

<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>

Hopefully this helps!



来源:https://stackoverflow.com/questions/16285947/how-can-i-fix-this-element-to-stick-at-the-top-of-the-page-on-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!