javascript 单击时向下滚动功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19899412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
scroll down function on click
提问by kcrocks
below is the code I have for scrollTop. It works fine when I target a specific pixel, but I want to scroll down 300px, instead of scrollTop a certain div on click. can anyone help?
下面是我为 scrollTop 编写的代码。当我针对特定像素时,它工作正常,但我想向下滚动 300 像素,而不是在单击时将某个 div 滚动到某个 div。有人可以帮忙吗?
<div id="button"></div>
<div1 style="height:300px;">img1</div>
<div2 style="height:300px;">img2</div>
<div3 style="height:300px;">img3</div>
<div4 style="height:300px;">img4</div>
$(function() {
$("#button").on("click", function() {
$("html, body"). animate({"scrollTop":$().offset().top-300}, 1000);
return false;
});
});
回答by jyothsna
Try using window.scrollBy(0,300);
尝试使用 window.scrollBy(0,300);
回答by megawac
$().offset().top
doesnt do much of anything. Replace it with window.scrollY
$().offset().top
什么都不做。将其替换为window.scrollY
$(function() {
$("#button").on("click", function() {
$("body").animate({"scrollTop": window.scrollY-300}, 1000);
return false;
});
});
Also negative is up and positive is down when we're talking about scrolling so you probably want to add 300 instead.
当我们谈论滚动时,负数上升,正数下降,因此您可能想要添加 300。
回答by user8973683
I think it's the best way.
我认为这是最好的方法。
var body = $('html, body');
$('#button').click(function() {
var n = $(document).height() - $(window).height();
body.stop().animate({scrollTop: n }, 1000, function() {
});
});