jQuery修复标题向下滑动滚动问题

时间:2014-08-03 13:40:48

标签: javascript jquery html css jquery-animate

我是jQuery的新手,请不要严格判断。当我滚动页面300px时,我希望标题固定。并删除固定if< 300px。我想为它设置动画,向下滚动时向下滑动,向上滚动时向上滑动。像这样Some site, scroll down and you'll see what I want.

我喜欢那样的HTML

<div class="heading-wrapper">
<a href="#">1 </a>
<a href="#"> 2</a>
<a href="#"> 3</a>
<a href="#">4</a>
<a href="#">5</a>    
</div>

的CSS

.heading-wrapper {
width: 100%;
height: 65px;
background: #000;
position: relative;
}

.heading-wrapper.fixed {
position: fixed;
top: -80px;
left: 0;
right: 0;
}

和jQuery

$(window).scroll(function() {
if ($(this).scrollTop() > 300){  
$('.heading-wrapper').addClass("fixed");
$('.heading-wrapper.fixed').animate({'top' : '0px'}, 800);
  }
  else{
$('.heading-wrapper.fixed').animate({'top' : '-80px'}, 800);
setTimeout(function(){
    $('.heading-wrapper').removeClass("fixed");
    },800); 
  }
});

它不像我想要的那样工作。

  1. 如果通过按下鼠标滚动 - 它不会动画..
  2. 动画只出现在..
  3. 幻灯片动画永远不会出现..
  4. 如果我快速上下滚动,整个结构都会崩溃,必要时不会添加任何样式))
  5. 请帮我解决这个问题,记住,不要严格判断! :)

    JsFiddle link

2 个答案:

答案 0 :(得分:3)

<强> Demo

JS

$(document).ready(function () {
    $("header").before($("header").clone().addClass("animateIt"));
    $(window).on("scroll", function () {
        $("body").toggleClass("down", ($(window).scrollTop() > 100));
    });
});

CSS

body, html {
    margin:0;
    padding:0;
}
header {
    position: relative;
    width: 100%;
    height: 60px;
    line-height: 60px;
    background: #000;
    color: #fff;
}
header.animateIt {
    position:fixed;
    top:-60px;
    left: 0;
    right: 0;
    z-index:999;
    transition:0.4s top cubic-bezier(.3, .73, .3, .74);
}
body.down header.animateIt {
    top:0;
}
.content {
    padding: 0 20px 20px;
    background: #fff;
    line-height: 1.5;
    color: #333;
}

HTML

<header>
    <a href="#">1 </a>
    <a href="#"> 2</a>
    <a href="#"> 3</a>
    <a href="#">4</a>
    <a href="#">5</a>    
</header>

答案 1 :(得分:1)

这是我将如何做到的。

首先,根据您支持的浏览器,您可以添加此CSS:

.heading-wrapper {
   position: fixed;
   top: -80px;
   transition: top 1s linear; /*as you wish*/
   [...]
}

.heading-wrapper.relative {
    position: absolute;
    top: 0px;
}

.heading-wrapper:not(.relative).fixed {
    top: 0px;
}

然后在Javascript中:

var $wrapper = $(".heading-wrapper");
var $win = $(window);
var doc = document.documentElement, body = document.body;
var top = 0;

$wrapper.clone().appendTo("body").addClass("relative");

$win.scroll(function () {
   top = (doc && doc.scrollTop  || body && body.scrollTop  || 0);
   if( top > 300)
       setTimeout(function(){$wrapper.addClass("fixed");},0);
   else if( $wrapper.hasClass("fixed") )
      setTimeout(function(){$wrapper.removeClass("fixed");},0);
});

我更新了您的JSFiddle

编辑:添加了一个克隆的菜单,绝对。

相关问题