jQuery:单击时向下滚动页面设置增量(以像素为单位)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2659354/
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
jQuery: Scroll down page a set increment (in pixels) on click?
提问by bcWeb
I'm trying to make a page scroll down 150px from the current position when an element is clicked. So lets say you're roughly halfway scrolled down a page. You click this link, and it will slide you down an additional 150 pixels.
当单击元素时,我试图使页面从当前位置向下滚动 150 像素。因此,假设您大致向下滚动了页面的一半。您单击此链接,它会将您再向下滑动 150 像素。
Is this possible with jQuery?
这可以用 jQuery 实现吗?
I've been looking at scrollTop and the scrollTo plugin, but I can't seem to connect the dots.
我一直在研究 scrollTop 和 scrollTo 插件,但我似乎无法将这些点联系起来。
回答by Mohamed Hafez
var y = $(window).scrollTop(); //your current y position on the page
$(window).scrollTop(y+150);
回答by Yatin Khullar
Just check this:
只需检查一下:
$(document).ready(function() {
$(".scroll").click(function(event){
$('html, body').animate({scrollTop: '+=150px'}, 800);
});
});
It will make scroller scroll from current position when your element is clicked
当您的元素被单击时,它将使滚动条从当前位置滚动
And 150px is used to scroll for 150px downwards
而 150px 用于向下滚动 150px
回答by Mahesh Velaga
You can do that using animate
like in the following link:
您可以使用animate
以下链接中的类似方法执行此操作:
http://blog.freelancer-id.com/index.php/2009/03/26/scroll-window-smoothly-in-jquery
http://blog.freelancer-id.com/index.php/2009/03/26/scroll-window-smoothly-in-jquery
If you want to do it using scrollTo
plugin, then take a look the following:
如果您想使用scrollTo
插件来完成,请查看以下内容:
回答by Dymos
You might be after something that the scrollTo plugin from Ariel Flesler does really well.
您可能正在寻找 Ariel Flesler 的 scrollTo 插件做得非常好的东西。
回答by Martin54
Pure js solution for newcomers or anyone else.
适用于新手或其他任何人的纯 js 解决方案。
var scrollAmount = 150;
var element = document.getElementById("elem");
element.addEventListener("click", scrollPage);
function scrollPage() {
var currentPositionOfPage = window.scrollY;
window.scrollTo(0, currentPositionOfPage + scrollAmount);
}
回答by Pixelomo
Updated version of HCD's solution which avoids conflict:
避免冲突的 HCD 解决方案的更新版本:
var y = $j(window).scrollTop();
$j("html, body").animate({ scrollTop: y + $j(window).height() }, 600);