2013-10-25 305 views
0

我使滚动顶部和滚动到底部jquery。在这一点上,我使用百分比滚动。例如: 如果从上到下滚动是50%那么它从上到下滚动为50%它已经工作。但是现在我想滚动50%,如果再次单击,则将剩余的50%滚动到页面底部。我不知道如何在jQuery中做到这一点。滚动顶部jquery

这里是小提琴任何建议将是伟大的。 http://jsfiddle.net/TkYpY/

感谢, 玉萍

+0

你的问题不清楚 - 你想达到什么目的?一次滚动总距离的50%似乎很奇怪,因为你永远不会到达顶部或底部。 –

+0

在你的jsfiddle中,即使顶部和底部也不起作用。你有没有考虑过检查[scrollTo](http://flesler.blogspot.com/2007/10/jqueryscrollto.html)?它非常方便,可能会帮助你很多。 –

回答

1
$('#spnTop').on("click", function() { 
var percentageToScroll = 50; 
var percentage = percentageToScroll/100; 
var height = $(document).height() - $(window).height(); 
if(scrollAmount > 0) 
{ 
scrollAmount = scrollAmount - (height * percentage); 
} 

console.log('scrollAmount: ' + scrollAmount); 
$('html,body').animate({ 
    scrollTop: scrollAmount 
}, 'slow', function() { 
    console.log("reached top"); 
}); 

}); 

var scrollAmount = 0; 
$('#spnbottom').on("click", function() { 
var percentageToScroll = 50; 
var percentage = percentageToScroll/100; 
var height = $(document).height() - $(window).height(); 

if( scrollAmount < height) 
{ 
scrollAmount = scrollAmount + height * percentage; 
} 
console.log('scrollAmount: ' + scrollAmount); 
jQuery("html, body").animate({ 
    scrollTop: scrollAmount 
}, 900); 
}); 
1

它不会在第二次点击滚动,你已经达到了scrollAmount。

如果您想进一步滚动,请在函数外面声明var scrollAmount,并且当您再次点击底部链接时,计算下一个滚动值,其中max是文档高度,并将其添加到全局scrollAmount声明的var。

1
$('#spnTop').on("click", function() { 
var percentageToScroll = 80; 
var percentage = percentageToScroll/100; 
var height = $(document).scrollTop(); 
var scrollAmount = height * (1 - percentage); 

console.log('scrollAmount: ' + scrollAmount); 
$('html,body').animate({ 
    scrollTop: scrollAmount 
}, 'slow', function() { 
    console.log("reached top"); 
}); 

});

var scrollAmount = 0; 
$('#spnbottom').on("click", function() { 
var percentageToScroll = 50; 
var percentage = percentageToScroll/100; 
var height = $(document).height() - $(window).height(); 
scrollAmount = scrollAmount + height * percentage; 
console.log('scrollAmount: ' + scrollAmount); 
jQuery("html, body").animate({ 
    scrollTop: scrollAmount 
}, 900); 
}); 
+0

我刚刚在你的jsfiddle中修改了两行。 var scrollAmount = 0;和scrollAmount = scrollAmount + height * percentage; –

+0

谢谢@Girish Sakhare它的工作原理。你能告诉我从底部到顶部做同样的事吗? –

+0

嗨@Vicky只做同样的事情 - scrollAmount,如果它> 0。scrollAmount = scrollAmount - (height *(1 - percentage)); –

1

我修改了一下你的小提琴。对我来说似乎有一些计算问题。 Here is your fiddle。 这是你需要的吗?

首先用默认值声明一个全局变量height

在顶部滚动码,与 height -= $(document).height() - $(window).height();

取代 var height = $(document).scrollTop(); 和底部滚动与height += $(document).height() - $(window).height();替换此var height = $(document).height() - $(window).height();

+0

我试过你的代码,这是我想要的。从底部到顶部30%滚动到顶部,然后再次点击100%。我想它本身就是30%。例如,如果我提到20%意味着五次点击达到最高。希望你明白了我的观点是否有一种方法可以显示与 –

+0

相同的输出你可以使用一个包含你提到的百分比的变量,即20%或30%或任何你想要的。在函数内部,您可以相应地添加或减去此变量。 –

+0

从你的小提琴本身的感谢从底部到顶部只有一次,然后再次如果我点击它去顶部没有相应的百分比,你注意到了吗? –