jQuery缓动插件,负向scrollTop,到达顶部或底部

时间:2015-06-02 19:11:46

标签: jquery html css easing

我创建了一个简单的单页网站,我在使用缓动插件时遇到了问题,当从第一页移到第二页时,顶部没有足够的空间来预测"预期" (动画术语),也不是在底部向上移动到第二页。请看我的代码演示,谢谢。

请在这里看到演示http://jsfiddle.net/56vmztjn/ StackExchange的演示,表现得很有趣......



jQuery.extend( jQuery.easing,
{
	def: 'easeInBack',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	}, easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	}
});
// utility
function onePage(el) {
	var windowWidth = $(window).width(),
		windowHeight = $(window).height(),
		next = el.next('.onePage'),
		prev = el.prev('.onePage');
	el.width(windowWidth);
	el.css({"min-height":windowHeight});
	
	el.find('.next').on('click', function() {
		goTo(el, next);
	});
	el.find('.prev').on('click', function() {
		goTo(el, prev);
	});
}
function goTo(start, end) {
	var ini = start.offset().top,
		destination = end.offset().top, 
		distance = Math.abs(ini - destination),
		speed = distance/1.5; 
	$('html body').animate({
		scrollTop : destination
	}, speed);
}
// on ready
$(document).ready(
	function() {
		$('.onePage').each(
			function(index, el) {
				onePage($(el));
			}
		);
	}
);

body, html {
  padding:0; margin:0;
}
.onePage {
  padding: 2em;
}
.a {
    background:red;
}
.b {
    background:yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="onePage a">
  <button class="next">next</button>
  <button class="prev">prev</button>
  <h1>page 1</h1>
</div>
<div class="onePage b">
  <button class="next">next</button>
  <button class="prev">prev</button>
  <h1>page 2</h1>
</div>  
<div class="onePage a">
  <button class="next">next</button>
  <button class="prev">prev</button>
  <h1>page 3</h1>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

根据评论中的对话,如果您希望第一页和最后一页使用“缓动”插件来显示动画,则需要您的网站拥有额外的空间在页面的顶部和底部。

HTML

<div class="extraspace"></div>
<div class="onePage a top">
  <button class="next">next</button>
  <button class="prev">prev</button>
  <h1>page 1</h1>
</div>
<div class="onePage b">
  <button class="next">next</button>
  <button class="prev">prev</button>
  <h1>page 2</h1>
</div>  
<div class="onePage a">
  <button class="next">next</button>
  <button class="prev">prev</button>
  <h1>page 3</h1>
</div>
<div class="extraspace"></div>

CSS,添加此

.extraspace {
    height:50px;
}

这样做会在页面的顶部和底部增加额外的高度,因此拉动画将起作用,但在页面加载时,顶部有一个额外的空间,因此我们需要在页面加载时将使用导航到正确的区域。我们可以用JQuery做到这一点:

$( document ).ready(function() {
    $('html, body').animate({scrollTop: "50px"}, 1);
});

唯一的缺点是用户可以手动滚动到额外的空格部分。希望这会有所帮助。