2017-10-12 102 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>