我有这个输入元素:
<input type="text" class="textfield" value="" id="subject" name="subject">
然后我还有一些其他元素,比如其他标签的&<textarea>标签等等。。。
当用户点击<input id=“#subject”>时,页面应该滚动到页面的最后一个元素,并且应该使用一个漂亮的动画(应该滚动到底部而不是顶部)。
页面的最后一项是带有#submit的提交按钮:
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
动画不应该太快,应该是流畅的。
我正在运行最新的jQuery版本。我宁愿不安装任何插件,而是使用默认的jQuery特性来实现这一点。
我就是这样做的。
document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })
适用于任何浏览器。
它可以很容易地包装成函数
function scrollTo(selector) {
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })
}
下面是一个工作示例$(“.btn”).click(函数){document.getElementById(“scrollHere”).sollIntoView({behavious:“smooth”})}).btn{margin-bottom:500px;}.middle{显示:块;边距底部:500px;颜色:红色;}<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js“></script><button class=“btn”>向下滚动</button><h1 class=“middle”>看到了吗</h1><div id=“scrollHere”>到达目的地</div>
Docs
当用户点击带有#subject的输入时,页面应该滚动到页面的最后一个元素并添加一个漂亮的动画。它应该是向下滚动而不是向上滚动。页面的最后一项是带有#submit的提交按钮
$('#subject').click(function()
{
$('#submit').focus();
$('#subject').focus();
});
这将首先向下滚动到#submit,然后将光标恢复到单击的输入,这模拟向下滚动,适用于大多数浏览器。它也不需要jQuery,因为它可以用纯JavaScript编写。
通过链接焦点调用,这种使用焦点函数的方式可以更好地模拟动画吗。我还没有测试过这个理论,但它看起来像这样:
<style>
#F > *
{
width: 100%;
}
</style>
<form id="F" >
<div id="child_1"> .. </div>
<div id="child_2"> .. </div>
..
<div id="child_K"> .. </div>
</form>
<script>
$('#child_N').click(function()
{
$('#child_N').focus();
$('#child_N+1').focus();
..
$('#child_K').focus();
$('#child_N').focus();
});
</script>
使用此解决方案,您不需要任何插件,并且除了在关闭</body>标记之前放置脚本外,不需要进行任何设置。
$("a[href^='#']").on("click", function(e) {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top
}, 1000);
return false;
});
if ($(window.location.hash).length > 1) {
$("html, body").animate({
scrollTop: $(window.location.hash).offset().top
}, 1000);
}
加载时,如果地址中有哈希,我们会滚动到它。
而且,每当您单击带有href哈希的链接(例如#top)时,我们都会滚动到它。
##编辑2020
如果你想要一个纯JavaScript的解决方案:你可以使用类似的方法:
var _scrollToElement = function (selector) {
try {
document.querySelector(selector).scrollIntoView({ behavior: 'smooth' });
} catch (e) {
console.warn(e);
}
}
var _scrollToHashesInHrefs = function () {
document.querySelectorAll("a[href^='#']").forEach(function (el) {
el.addEventListener('click', function (e) {
_scrollToElement(el.getAttribute('href'));
return false;
})
})
if (window.location.hash) {
_scrollToElement(window.location.hash);
}
}
_scrollToHashesInHrefs();