jQuery滚动到元素 [英] jQuery scroll to element
问题描述
我有输入
元素:
<input type="text" class="textfield" value="" id="subject" name="subject">
然后我还有其他一些元素,比如其他文本输入,textareas等。
Then I have some other elements, like other text inputs, textareas, etc.
当用户使用 #subject
点击输入
时,页面应该使用漂亮的动画滚动到页面的最后一个元素。它应该是一个滚动到底部而不是顶部。
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.
该页面的最后一项是 submit
按钮 #submit
:
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.
我正在运行最新的jQuery版本。我更喜欢不安装任何插件,而是使用默认的jQuery功能来实现这一点。
I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.
推荐答案
假设你有一个按钮id 按钮
,试试这个例子:
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);
});
我从文章 顺利滚动到没有jQuery插件的元素 。我已在下面的示例中对其进行了测试。
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屋!