我有这个输入元素:
<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
如果您对平滑滚动效果不太感兴趣,而只是对滚动到特定元素感兴趣,则不需要使用jQuery函数。Javascript已涵盖您的案例:
https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
因此,您需要做的就是:$(“selector”).get(0).scrollIntoView();
使用.get(0)是因为我们希望检索JavaScript的DOM元素,而不是JQuery的DOM元素。
更新
现在可以通过滚动选项滚动动画(参见MDN)。您甚至可以控制块的位置。除了Safari,它似乎有很大的支持
$("selector").get(0).scrollIntoView({behavior: 'smooth'});
动画:
// slide to top of the page
$('.up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// slide page to anchor
$('.menutop b').click(function(){
//event.preventDefault();
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
return false;
});
// Scroll to class, div
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#target-element").offset().top
}, 1000);
});
// div background animate
$(window).scroll(function () {
var x = $(this).scrollTop();
// freezze div background
$('.banner0').css('background-position', '0px ' + x +'px');
// from left to right
$('.banner0').css('background-position', x+'px ' +'0px');
// from right to left
$('.banner0').css('background-position', -x+'px ' +'0px');
// from bottom to top
$('#skills').css('background-position', '0px ' + -x + 'px');
// move background from top to bottom
$('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');
// Show hide mtop menu
if ( x > 100 ) {
$( ".menu" ).addClass( 'menushow' );
$( ".menu" ).fadeIn("slow");
$( ".menu" ).animate({opacity: 0.75}, 500);
} else {
$( ".menu" ).removeClass( 'menushow' );
$( ".menu" ).animate({opacity: 1}, 500);
}
});
// progres bar animation simple
$('.bar1').each(function(i) {
var width = $(this).data('width');
$(this).animate({'width' : width + '%' }, 900, function(){
// Animation complete
});
});