jQuery – 滚动时缩小的粘滞标题

我想知道当你向下滚动页面时,如何制作一个粘滞的标题缩小(用animation),当页面向上滚动时返回正常状态。 这里有两个例子要清楚:

Home – Landing Page

Homepage

我得到的一部分,使其固定,但我应该怎么做,当用户滚动缩小我的标题?

万分感谢

这应该是你正在寻找使用jQuery的。

$(function(){ $('#header_nav').data('size','big'); }); $(window).scroll(function(){ if($(document).scrollTop() > 0) { if($('#header_nav').data('size') == 'big') { $('#header_nav').data('size','small'); $('#header_nav').stop().animate({ height:'40px' },600); } } else { if($('#header_nav').data('size') == 'small') { $('#header_nav').data('size','big'); $('#header_nav').stop().animate({ height:'100px' },600); } } }); 

示范: http : //jsfiddle.net/jezzipin/JJ8Jc/

这里是一个jezzipin的解决scheme的CSSanimation分支,从样式分离代码。

JS:

 $(window).on("scroll touchmove", function () { $('#header_nav').toggleClass('tiny', $(document).scrollTop() > 0); }); 

CSS:

 .header { width:100%; height:100px; background: #26b; color: #fff; position:fixed; top:0; left:0; transition: height 500ms, background 500ms; } .header.tiny { height:40px; background: #aaa; } 

http://jsfiddle.net/sinky/S8Fnq/

在scroll / touchmove中,如果$(document).scrollTop()大于0,那么css类“tiny”将被设置为“#header_nav”。

CSS转换属性很好地激发了“高度”和“背景”属性。

http://callmenick.com/2014/02/18/create-an-animated-resizing-header-on-scroll/

这个链接有一个很好的教程,包含你可以使用的源代码,展示如何使头部中的元素更小以及头部本身。

基于twitter滚动的麻烦( http://ejohn.org/blog/learning-from-twitter/ )。

这是我的解决scheme,限制js滚动事件(有用的移动设备)

JS:

 $(function() { var $document, didScroll, offset; offset = $('.menu').position().top; $document = $(document); didScroll = false; $(window).on('scroll touchmove', function() { return didScroll = true; }); return setInterval(function() { if (didScroll) { $('.menu').toggleClass('fixed', $document.scrollTop() > offset); return didScroll = false; } }, 250); }); 

CSS:

 .menu { background: pink; top: 5px; } .fixed { width: 100%; position: fixed; top: 0; } 

HTML:

 <div class="menu">MENU FIXED ON TOP</div> 

http://codepen.io/anon/pen/BgqHw

我做了一个Jezzipin的答案的升级版本(和我的animation填充顶部而不是高度,但你仍然明白了。

  /** * ResizeHeaderOnScroll * * @constructor */ var ResizeHeaderOnScroll = function() { this.protocol = window.location.protocol; this.domain = window.location.host; }; ResizeHeaderOnScroll.prototype.init = function() { if($(document).scrollTop() > 0) { $('header').data('size','big'); } else { $('header').data('size','small'); } ResizeHeaderOnScroll.prototype.checkScrolling(); $(window).scroll(function(){ ResizeHeaderOnScroll.prototype.checkScrolling(); }); }; ResizeHeaderOnScroll.prototype.checkScrolling = function() { if($(document).scrollTop() > 0) { if($('header').data('size') == 'big') { $('header').data('size','small'); $('header').stop().animate({ paddingTop:'1em', paddingBottom:'1em' },200); } } else { if($('header').data('size') == 'small') { $('header').data('size','big'); $('header').stop().animate({ paddingTop:'3em' },200); } } } $(document).ready(function(){ var resizeHeaderOnScroll = new ResizeHeaderOnScroll(); resizeHeaderOnScroll.init() })