您将不得不使用 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>
希望这会有所帮助!