2017-10-12 82 views
1

我試圖只在一定的滾動長度後創建一個div visibe。 關於它的Stackoverflow已經有一些線程了,所以我試圖使用在答案中列出的建議腳本,但是其中沒有一個似乎能夠工作。在哪裏添加一個腳本來執行滾動操作?

所以,我想我不知道如何使用它們。

我已經把這個塊到head,由兩個script標籤包圍:

function scroll_bar() { 
    if (document.body.scrollTop > 700) { 
     document.getElementById("navigation_bar").show(); 
    } 
    else 
    { 
     document.getElementById("navigation_bar").hide(); 
    } 
} 

而在body,我有一個div(我想使人們看到了一個/隱藏)與這些屬性:

<div onload="scroll_bar();" class="container" id="navigation_bar" style="position: fixed; z-index: 1; background-color: white; height: 50px; width: 100%;"></div> 

這裏有什麼問題? (我用引導無論如何,這「容器」類來自它。)

+0

隨着「好像不行」我的意思是,它並沒有在任何意義上的功能作出反應,就好像它不」不存在。 – Antonio

+0

移除位置:固定並檢查 –

+0

不,我想在滾動過程中將它固定到頂部(位於頂部,位於z-index 1上)... – Antonio

回答

0

而不是把你的<script><head>,放在只是你的結束標記(</body>)前。這將確保內容在腳本之前加載,因此您的腳本應該正確運行。

<p>I'm some content!</p> 

    <script>console.log('JavaScript!');</script> 

</body> 

此外,還需要確保在the body scroll event.

2

你的腳本功能火災您可以選擇將事件監聽器添加到「滾動」事件:window.addEventListener('scroll', scroll_bar)。同樣在你的處理程序中,我會使用的document.body.scrollTop

+0

在哪裏我可以添加聽衆? – Antonio

+0

解決。 :)我已經把它放到body屬性中,作爲... onscroll =「window.addEventListener('scroll',scroll_bar) – Antonio

0

難道你確定它很好?

document.getElementById("navigation_bar").show(); 

「的document.getElementById(」 navigation_bar 「)。」是javascript。

「show()」是jquery。

嘗試:

document.getElementById("navigation_bar").style.display = 'block'/'none' 

$("#navigation_bar").show(); 
+0

哦,非常感謝,我不知道這一點。無論如何,包括jquery因爲我使用Bootstrap,它在默認情況下... – Antonio

0

你放錯了地方的事件覈實。

請動你的事件BODY

代碼

<body onload="scroll_bar();" > 
<div class="container" id="navigation_bar" style="position: fixed; z-index: 1; background-color: white; height: 50px; width: 100%;"></div> 
</body> 
相關問題