我有这个输入元素:

  <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特性来实现这一点。


当前回答

使用此简单脚本

if($(window.location.hash).length > 0){
        $('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
}

如果在url中找到了哈希标记,则滚动到ID。如果没有找到哈希标记,那么忽略脚本。

其他回答

jQuery(document).ready(函数($){$('a[href^=“#”]').bind('click.s平滑滚动',函数(e){e.预防违约();var目标=this.hash,$target=$(目标);$('html,body').stop().animate({“scrollTop”:$target.offset().top-40},900,'摆动',函数(){window.location.hash=目标;} );} );} );<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”>第1节</a></li><li id=“p2”><a href=“#pane2”role=“tab”>第2节</a></li><li id=“p3”><a href=“#pane3”role=“tab”>第3节</a></li></ul><div id=“pane1”></div><div id=“pane2”></div><div id=“pane3”></div>

在大多数情况下,最好使用插件。认真地我要在这里兜售我的。当然还有其他的。但请检查他们是否真的避免了那些你首先想要插件的陷阱——并不是所有人都这样做。

我写过在其他地方使用插件的原因。简而言之,这里大多数答案的基础是一行

$('html, body').animate( { scrollTop: $target.offset().top }, duration );

是糟糕的用户体验。

动画不会响应用户操作。即使用户单击、轻击或尝试滚动,它也会继续。如果动画的起点接近目标元素,则动画会非常缓慢。如果目标元素位于页面底部附近,则无法滚动到窗口顶部。然后,滚动动画在中间运动时突然停止。

为了处理这些问题(以及其他一些问题),您可以使用我的插件jQuery.scrollable

$( window ).scrollTo( targetPosition );

就这样。当然,还有更多的选择。

关于目标位置,在大多数情况下,$target.offset().top完成任务。但是请注意,返回的值没有考虑html元素上的边框(请参见本演示)。如果你需要目标位置在任何情况下都准确,最好使用

targetPosition = $( window ).scrollTop() + $target[0].getBoundingClientRect().top;

即使在html元素上设置了边框,这也能正常工作。

您只需要:

$("selector").get(0).scrollTo(0, 0)

单线的,单线的

subject.onclick = e=> window.scroll({ top: submit.offsetTop, behavior: 'smooth'});

subject.onclick=e=>window.sollow({top:submit.offsetTop,behavior:“smooth”});.box,.foot{display:flex;background:#fdf;padding:500px 0}.foot{padding:250px}<input type=“text”class=“textfield”value=“click here”id=“subject”name=“subject”><div class=“box”>一些内容<textarea></textarea></div><input type=“submit”class=“submit”id=“submit“name=”submit“value=”Ok,Done“><div class=“foot”>一些页脚</div>

这是Atharva的回答:https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView.只是想补充一下,如果您的文档在iframe中,您可以在父框架中选择一个元素滚动到视图中:

 $('#element-in-parent-frame', window.parent.document).get(0).scrollIntoView();