2015-10-29 59 views
0

我想在javascript中滾動幾個像素後粘住我的菜單欄,但它不能正常工作。這是我的腳本。

JavaScript代碼:用於固定菜單位置的Javascript滾動條

window.onscroll = function() {stick()}; 

function stick() { 
    if (document.body.scrollTop || document.documentElement.scrollTop > 150) { 
     document.getElementById("test").style.position = "fixed"; 
     document.getElementById("test").style.background = "blue"; 
    } else { 
     document.getElementById("test").style.position = "initial"; 
    } 
} 

問題:
每當我滾動甚至一個像素在我的測試ID得到固定。我試圖在if中改變scrollTop的值,但沒有效果。任何關注將不勝感激。

更新: 這裏也是使用ID的錯誤。

<script> 
document.getElementById("cntnr").onscroll = function() {stick()}; 

function stick() { 
    if (document.getElementById("cntnr").scrollTop > 119) { 
    document.getElementById("navdwn").style.position = "fixed"; 
    } else { 
    document.getElementById("navdwn").style.position = "initial"; 
    } 
} 
</script> 
+0

你試過(位置)絕對而不是固定的? –

+0

@MalithMcR他的if條件是錯誤的,當他向下滾動時總是會有代碼在if條件執行時, – Arjun

+0

爲你的代碼創建JSfiddle –

回答

4

驗證If條件,解決滾動到150像素菜單當前文檔頂部

變化:

window.onscroll = function() {stick()}; 

function stick() { 
if (document.body.scrollTop > 150) { 
    document.getElementById("test").style.position = "fixed"; 
    document.getElementById("test").style.background = "blue"; 
} else { 
    document.getElementById("test").style.position = "initial"; 
} 
} 
+0

謝謝,它的作品.....乾杯。 :) –

+0

是的。如果它可以幫助你將它標記爲答案 – Arjun

+0

,但同樣的方法不適用於ids ...... wait我發佈更新 –

1

試試這個代碼,你需要的JavaScript的parseInt函數()函數來使 document.documentElement.scrollTop等於整數

window.onscroll = function() {stick()}; 

var offset = document.documentElement.scrollTop 

function stick() { 
    if (parseInt(offset) > 150) { 
     document.getElementById("test").style.position = "fixed"; 
     document.getElementById("test").style.background = "blue"; 
    } else { 
     document.getElementById("test").style.position = "initial"; 
    } 
} 
+0

感謝您的關注 –

+0

你有試過嗎? –

+0

這是好的,但阿瓊指出我的錯誤。 –

1

只要開始滾動,document.body.scrollTop的值就會大於0。如果第一個條件爲真,運營商將不檢查第二個條件。

因此,只要您開始滾動,第一個條件變爲true,然後測試ID得到修復。

更改條件爲if (document.body.scrollTop > 150) {....,它會工作。