我有这个输入元素:

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


当前回答

单线的,单线的

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>

其他回答

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>

我就是这样做的。

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

“动画”解决方案的精简版。

$.fn.scrollTo = function (speed) {
    if (typeof(speed) === 'undefined')
        speed = 1000;

    $('html, body').animate({
        scrollTop: parseInt($(this).offset().top)
    }, speed);
};

基本用法:$('#your_element').sollTo();

jQuery.sollTo():视图-演示,API,源代码

我编写了这个轻量级插件,使页面/元素滚动更加容易。它很灵活,可以传入目标元素或指定值。也许这可能是jQuery下一次正式发布的一部分,你觉得呢?


示例用法:

$('body').scrollTo('#target'); // Scroll screen to target element

$('body').scrollTo(500); // Scroll screen 500 pixels down

$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down

选项:

scrollTarget:指示所需滚动位置的元素、字符串或数字。

offsetTop:定义滚动目标上方额外间距的数字。

duration:一个字符串或数字,决定动画将运行多长时间。

easing:一个字符串,指示用于转换的缓和函数。

complete:动画完成后调用的函数。

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

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