您必须使用Javascript来测试元素在页面上的位置(“myElement”),而不是页面滚动的距离。如果页面已经滚动到元素之外,那么您可以更改元素的CSS以将其捕捉到页面的顶部。注意:移动浏览器不喜欢“位置:固定”;风格的财产。
给你的元素“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>
希望这有助于!
该元素距离顶部约340像素。通过了解这些信息会有帮助吗? – user2333298 2013-04-30 03:10:22
非常感谢你! 最后一个问题:当我向下滚动搜索栏时向左移动。我试着做'myelement.style.text-align =“center”但无济于事。 有什么建议吗? – user2333298 2013-04-30 18:38:30
一旦你完全定位你的元素(固定),你将不得不使用“myElement.style.left ='200px';”或者将搜索框居中放置的像素数量。如果您使用响应式布局,则必须使用百分比。 – 2013-04-30 20:01:19