我如何修复这个元素粘在页面的顶部滚动? [英] How can I fix this element to stick at the top of the page on scroll?

查看:188
本文介绍了我如何修复这个元素粘在页面的顶部滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的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!

我使用本教程中的Javascript:在滚动时将对象修复到浏览器窗口的顶部

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.

有任何建议吗?

推荐答案

您将不得不使用Javascript来测试页面上的元素(myElement)的位置与页面滚动的距离。如果页面已经向上滚动超过你的元素,那么你改变你的元素的CSS,以抓到页面的顶部。注意:移动浏览器不喜欢position:fixed;

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.

为您的元素添加myElement的ID并将其插入到您的标签中。

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>

希望这有助于!

这篇关于我如何修复这个元素粘在页面的顶部滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆