jQuery .hide()滚动位置

时间:2014-03-19 11:02:35

标签: javascript jquery twitter-bootstrap hide show-hide

我想在我的单页网站的第一部分隐藏我的Bootstrap-Navbar,并在滚动到第一部分时将其淡入。

我尝试使用jQuery .hide()效果,告诉它在scrollTop为<时隐藏导航栏。 300px并在下面淡入 - 这工作正常,但第一次页面加载导航栏没有隐藏,就在我第一次向下滚动后,我无法弄清楚原因。

这是我的代码:

$('#wrapper').scroll(function(){
if($(this).scrollTop() < 300) $('#navbar').hide('easing');
if($(this).scrollTop() > 300) $('#navbar').fadeIn('slow');
});

以下是jsfiddle

我该怎么做?

5 个答案:

答案 0 :(得分:0)

我认为这是因为#navbar元素最初并未隐藏。

只需使用css隐藏它:

#navbar {
    height:50px;
    background-color:green;
    position:fixed;
    top:20px;
    width:100%;
    display: none;
}

演示:http://jsfiddle.net/Ub4xm/17/

答案 1 :(得分:0)

您应该在启动时将栏设置为隐藏,无论是CSS(干净)还是HTML(快速和脏)。

jQuery的.hide()将显示设置为&#34; none&#34;如果我是正确的,那么将页面加载时的显示设置为&#34; none&#34;,因为.fadeIn()会将显示设置为&#34;阻止&#34;。

答案 2 :(得分:0)

将显示添加到无:

#navbar {
  height:50px;
  background-color:green;
  position:fixed;
  top:20px;
  width:100%;
  display:none; /* <--add this*/
}

或在您的js中,您可以在doc ready中触发.scroll()

$(document).ready(function () {
  $('#wrapper').scroll(function () {
     if ($(this).scrollTop() < 300) {
         $('#navbar').hide('easing');
     } else if ($(this).scrollTop() > 300) {
         $('#navbar').fadeIn('slow');
     }
  }).scroll(); // <-----trigger it here first.
});

上面的代码可让您在doc准备就绪时看到带缓动的隐藏。

答案 3 :(得分:0)

首先在加载时隐藏#navbar。

$( document ).ready(function() {

    $('#navbar').hide();

    $('#wrapper').scroll(function(){
      if($(this).scrollTop() < 300) $('#navbar').hide('easing');
      if($(this).scrollTop() > 300) $('#navbar').fadeIn('slow');
    });
});

demo

答案 4 :(得分:-1)

试试这个

HTML

<div id="navbar" style="display:none">Teasers Div</div>

脚本

$( document ).ready(function() {
  $('#wrapper').scroll(function(){
  if($(this).scrollTop() > 300) 
    $('#navbar').fadeIn('slow');
  else
    $('#navbar').hide('easing');
  });
});

DEMO