您必須使用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