我有这个输入元素:

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


当前回答

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

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

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

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

其他回答

假设您有一个带有id按钮的按钮,请尝试以下示例:

$("#button").click(function() {
    $([document.documentElement, document.body]).animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 2000);
});

我从没有jQuery插件的文章平滑滚动到一个元素中得到了代码。我已经在下面的示例中测试了它。

<html><script src=“https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js“></script><脚本>$(文档).ready(函数(){$(“#click”).click(函数(){$('html,body').animate({scrollTop:$(“#div1”).offset().top}, 2000);});});</script><div id=“div1”style=“height:1000px;width 100px”>测验</div><br/><div id=“div2”style=“height:1000px;width 100px”>测试2</div><button id=“click”>单击我</button></html>

史蒂夫和彼得的解决方案非常有效。

但在某些情况下,您可能必须将该值转换为整数。奇怪的是,$(“…”).offset().top返回的值有时是浮点数。使用:parseInt($(“…”).offset().top)

例如:

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: parseInt($("#elementtoScrollToID").offset().top)
    }, 2000);
});

这是我使用通用类选择器抽象ID和href的方法

$(函数){//可在任何地方使用的通用选择器$(“.js滚动到”).click(函数(e){//动态获取hrefvar destination=$(this).attr('href');//阻止href=“#”链接更改URL哈希(可选)e.预防违约();//动画滚动到目的地$('html,body').animate({scrollTop:$(destination).offset().top}, 500);});});<!-- 固定导航菜单示例--><ul class=“nav”><li><a href=“#section-1”class=“nav item js scroll to”>项目1</a></li><li><a href=“#section-2”class=“nav item js scroll to”>项目2</a></li><li><a href=“#section-3”class=“nav item js scroll to”>项目3</a></li></ul>

要显示整个元素(如果可以使用当前窗口大小):

var element       = $("#some_element");
var elementHeight = element.height();
var windowHeight  = $(window).height();

var offset = Math.min(elementHeight, windowHeight) + element.offset().top;
$('html, body').animate({ scrollTop: offset }, 500);

单线的,单线的

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>