Javascript jQuery 滚动到元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6677035/
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 to element
提问by DiegoP.
I have this input
element:
我有这个input
元素:
<input type="text" class="textfield" value="" id="subject" name="subject">
Then I have some other elements, like other text inputs, textareas, etc.
然后我还有一些其他元素,比如其他文本输入、文本区域等。
When the user clicks on that input
with #subject
, the page should scroll to the last element of the page with a nice animation. It should be a scroll to bottom and not to top.
当用户点击它input
时#subject
,页面应该滚动到页面的最后一个元素,并带有漂亮的动画。它应该是滚动到底部而不是顶部。
The last item of the page is a submit
button with #submit
:
页面的最后一项是一个submit
按钮,带有#submit
:
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
The animation should not be too fast and should be fluid.
动画不应该太快并且应该是流畅的。
I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.
我正在运行最新的 jQuery 版本。我更喜欢不安装任何插件,而是使用默认的 jQuery 功能来实现这一点。
回答by Steve
Assuming you have a button with the id button
, try this example:
假设您有一个带有 id 的按钮button
,请尝试以下示例:
$("#button").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.
我从文章Smoothly scroll to an element without a jQuery plugin 中得到了代码。我已经在下面的示例中对其进行了测试。
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
$("#click").click(function (){
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
});
});
</script>
<div id="div1" style="height: 1000px; width 100px">
Test
</div>
<br/>
<div id="div2" style="height: 1000px; width 100px">
Test 2
</div>
<button id="click">Click me</button>
</html>
回答by Timothy Perez
jQuery .scrollTo(): View - Demo, API, Source
jQuery .scrollTo():查看 - 演示、API、源代码
I wrote this lightweight plugin to make page/element scrolling much easier. It's flexible where you could pass in a target element or specified value. Perhaps this could be part of jQuery's next official release, what do you think?
我编写了这个轻量级插件来使页面/元素滚动更容易。您可以灵活地传入目标元素或指定值。也许这可能是 jQuery 下一个正式版本的一部分,你怎么看?
Examples Usage:
示例用法:
$('body').scrollTo('#target'); // Scroll screen to target element
$('body').scrollTo(500); // Scroll screen 500 pixels down
$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down
Options:
选项:
scrollTarget: A element, string, or number which indicates desired scroll position.
scrollTarget:指示所需滚动位置的元素、字符串或数字。
offsetTop: A number that defines additional spacing above scroll target.
offsetTop:定义滚动目标上方额外间距的数字。
duration: A string or number determining how long the animation will run.
持续时间:确定动画将运行多长时间的字符串或数字。
easing: A string indicating which easing function to use for the transition.
easing:一个字符串,指示用于过渡的缓动函数。
complete: A function to call once the animation is complete.
complete: 动画完成后调用的函数。
回答by Atharva
If you are not much interested in the smooth scroll effect and just interested in scrolling to a particular element, you don't require some jQuery function for this. Javascript has got your case covered:
如果您对平滑滚动效果不太感兴趣,而只是对滚动到特定元素感兴趣,那么您不需要为此使用一些 jQuery 函数。Javascript 已经涵盖了您的案例:
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
So all you need to do is: $("selector").get(0).scrollIntoView();
所以你需要做的就是: $("selector").get(0).scrollIntoView();
.get(0)
is used because we want to retrieve the JavaScript's DOM element and not the JQuery's DOM element.
.get(0)
使用它是因为我们想要检索 JavaScript 的 DOM 元素而不是 JQuery 的 DOM 元素。
回答by Warface
Using this simple script
使用这个简单的脚本
if($(window.location.hash).length > 0){
$('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
}
Would make in sort that if a hash tag is found in the url, the scrollTo animate to the ID. If not hash tag found, then ignore the script.
如果在 url 中找到散列标签,scrollTo 会根据 ID 设置动画。如果未找到哈希标记,则忽略该脚本。
回答by davidcondrey
jQuery(document).ready(function($) {
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate( {
'scrollTop': $target.offset().top-40
}, 900, 'swing', function () {
window.location.hash = target;
} );
} );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul role="tablist">
<li class="active" id="p1"><a href="#pane1" role="tab">Section 1</a></li>
<li id="p2"><a href="#pane2" role="tab">Section 2</a></li>
<li id="p3"><a href="#pane3" role="tab">Section 3</a></li>
</ul>
<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>
回答by Tejasvi Hegde
The solution by Steve and Peter works very well.
史蒂夫和彼得的解决方案非常有效。
But in some cases, you may have to convert the value to an integer. Strangely, the returned value from $("...").offset().top
is sometimes in float
.
Use: parseInt($("....").offset().top)
但在某些情况下,您可能必须将该值转换为整数。奇怪的是, from 的返回值$("...").offset().top
有时在float
.
用:parseInt($("....").offset().top)
For example:
例如:
$("#button").click(function() {
$('html, body').animate({
scrollTop: parseInt($("#elementtoScrollToID").offset().top)
}, 2000);
});
回答by Rezgar Cadro
A compact version of "animate" solution.
“动画”解决方案的紧凑版本。
$.fn.scrollTo = function (speed) {
if (typeof(speed) === 'undefined')
speed = 1000;
$('html, body').animate({
scrollTop: parseInt($(this).offset().top)
}, speed);
};
Basic usage: $('#your_element').scrollTo();
基本用法: $('#your_element').scrollTo();
回答by Edvard ?kerberg
This is the way I do it.
这就是我这样做的方式。
document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })
Works in any browser.
适用于任何浏览器。
It can easily be wrapped into a function
它可以很容易地包装成一个函数
function scrollTo(selector) {
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })
}
Here is a working example
这是一个工作示例
$(".btn").click(function() {
document.getElementById("scrollHere").scrollIntoView( {behavior: "smooth" })
})
.btn {margin-bottom: 500px;}
.middle {display: block; margin-bottom: 500px; color: red;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="btn">Scroll down</button>
<h1 class="middle">You see?</h1>
<div id="scrollHere">Arrived at your destination</div>
回答by GameMaster1928
I know a way without jQuery:
我知道一种没有 jQuery 的方法:
document.getElementById("element-id").scrollIntoView();
Edit: It's been two years and I'm still randomly getting reputation from this post lmao
编辑:已经两年了,我仍然随机从这篇文章中获得声誉 lmao
回答by Benjamin Oakes
If you are only handling scrolling to an input element, you can use focus()
. For example, if you wanted to scroll to the first visible input:
如果您只处理滚动到输入元素,则可以使用focus()
. 例如,如果您想滚动到第一个可见输入:
$(':input:visible').first().focus();
Or the first visible input in an container with class .error
:
或者具有 class 的容器中的第一个可见输入.error
:
$('.error :input:visible').first().focus();
Thanks to Tricia Ballfor pointing this out!
感谢Tricia Ball指出这一点!