使用 jQuery 滚动到一个元素 [英] Scroll to an element with jQuery
问题描述
我有这个 input
元素:
然后我还有一些其他元素,例如其他文本输入、文本区域等.
当用户使用 #subject
点击那个 input
时,页面应该滚动到页面的最后一个元素,并带有漂亮的动画.它应该滚动到底部而不是顶部.
页面的最后一项是带有 #submit
的 submit
按钮:
动画不能太快,应该流畅.
我正在运行最新的 jQuery 版本.我更喜欢不安装任何插件,而是使用默认的 jQuery 功能来实现这一点.
假设你有一个 id 为 button
的按钮,试试这个例子:
$("#button").click(function() {$([document.documentElement, document.body]).animate({scrollTop: $("#elementtoScrollToID").offset().top}, 2000);});
我从文章中得到了代码平滑滚动到一个没有 jQuery 插件的元素.我已经在下面的示例中对其进行了测试.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script><脚本>$(document).ready(function (){$("#click").click(function (){$('html, body').animate({scrollTop: $("#div1").offset().top}, 2000);});});<div id="div1" style="height: 1000px; width 100px">测试
<br/><div id="div2" style="height: 1000px; width 100px">测试 2
<button id="click">点击我</button></html>
I have this input
element:
<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.
The last item of the page is a submit
button with #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.
Assuming you have a button with the id button
, try this example:
$("#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.
<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>
这篇关于使用 jQuery 滚动到一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!