jQuery滚动到元素

Die*_*oP. 2196 javascript jquery

我有这个input元素:

<input type="text" class="textfield" value="" id="subject" name="subject">
Run Code Online (Sandbox Code Playgroud)

然后我有一些其他元素,如其他文本输入,textareas等.

当用户点击它input#subject,页面应滚动到页面的最后一个元素,并带有漂亮的动画.它应该是一个滚动到底部而不是顶部.

页面的最后一项是一个submit按钮,其中包含#submit:

<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
Run Code Online (Sandbox Code Playgroud)

动画不应该太快,应该是流畅的.

我正在运行最新的jQuery版本.我更喜欢不安装任何插件,但使用默认的jQuery功能来实现这一点.

Ste*_*eve 3884

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

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

我从文章Smoothly滚动到没有jQuery插件的元素的代码.我已经在下面的例子中对它进行了测试.

<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function (){
            $("#click").click(function (){
                $('html, body').animate({
                    scrollTop: $("#div1").offset().top
                }, 2000);
            });
        });
    </script>
    <div id="div1" style="height: 1000px; width 100px">
        Test
    </div>
    <br/>
    <div id="div2" style="height: 1000px; width 100px">
        Test 2
    </div>
    <button id="click">Click me</button>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 如果您不想要动画,而是想立即跳转到元素,请使用[`.scrollTop(...)`](http://api.jquery.com/scrollTop/)而不是`.animate({scrollTop :...},...)`. (71认同)
  • 这并不适用于所有情况.请参见http://stackoverflow.com/questions/2905867/how-to-scroll-to-specific-item-using-jquery (22认同)
  • 除了你的解决方案(效果很好)之外,你还可以添加一个完整的功能,将主题标签添加到网址中.在这种情况下,它不会滚动,因为scrollTo已经滚动到正确的位置,如果用户复制了URL,它将自动捕捉到页面上的正确位置. (10认同)
  • 如果你在动画完成时使用回调来运行并注意回调用这个解决方案触发两次,请尝试使用"$('html body').animate(..."而不是"$('html,body') .animate(..."逗号创建了两个动画事件.一个用于html,一个用于body.你真的只想要一个用于HTML身体谢谢@TJ Crowder http://stackoverflow.com/questions/8790752/callback-of -animate-得到所谓-两次的jQuery (8认同)
  • @BarryChapman不完全是.谷歌搜索后我发现[这](http://stackoverflow.com/questions/5231459/how-come-html-animate-only-works-in-ie-and-body-animate-is-needed),所以如果您不希望每种浏览器类型都有额外的逻辑,则需要两个标记. (7认同)
  • 谢谢!在我的情况下,我有一个添加偏移的导航栏,所以如果你有这种情况,请像我一样减去导航栏的高度(在我的情况下:80px):`scrollTop:$("#elementtoScrollToID").offset() .top - 80` (3认同)
  • 此功能使我的页面在执行前反弹.要停止使用'e.preventDefault();' 在你的功能'...点击(功能(e){...'. (2认同)
  • @FranciscoCorrales A [没有动画的jsFiddle](http://jsfiddle.net/roryokane/s7e8B/).在`click`处理函数中,写`$('html,body').scrollTop($("#div2").offset().top)`,它使用[`.offset()`](http: //api.jquery.com/offset/). (2认同)

Tim*_*rez 503

jQuery .scrollTo()方法

jQuery .scrollTo():View - Demo,API,Source

我写了这个轻量级插件,使页面/元素滚动更容易.它可以灵活地传递目标元素或指定值.也许这可能是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
Run Code Online (Sandbox Code Playgroud)

选项:

scrollTarget:表示所需滚动位置的元素,字符串或数字.

offsetTop:一个数字,用于定义滚动目标上方的附加间距.

duration:确定动画运行时间的字符串或数字.

easing:一个字符串,指示要用于转换的缓动函数.

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

  • $('body')在FF中不起作用,所以尝试了$('html,body'). (13认同)
  • 如果有人需要这个脚本源,那么你可以在这里获得它http://flesler.com/jquery/scrollTo/js/jquery.scrollTo-min.js (5认同)
  • @TimothyPerez:我确信这意味着允许商业用途?我确信有很多人想在他们的网站上的任何地方使用那段代码,这有助于他们在晚上睡得更轻松一点?也许MIT许可证可能适合您的需求?http://en.wikipedia.org/wiki/MIT_License (3认同)

Ath*_*rva 346

如果你对平滑滚动效果不太感兴趣并且只想滚动到特定元素,那么你不需要一些jQuery函数.Javascript已涵盖您的案例:

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView

所以你需要做的就是: $("selector").get(0).scrollIntoView();

.get(0) 之所以使用是因为我们想要检索JavaScript的DOM元素而不是JQuery的DOM元素.

  • @Gavin我确定你的意思是:`document.getElementById('elementID').scrollIntoView()` (56认同)
  • 如果您根本不想使用jQuery,只需使用`document.getElementById('#elementID').scrollIntoView()`.没有用于加载~100k库只是为了选择一个元素然后将其转换为常规JavaScript. (18认同)
  • RobW,是的你可以使用[0],但get(0)可以保护你免受未定义或负面索引的影响.查看来源:http://james.padolsey.com/jquery/#v=1.10.2&fn=jQuery.fn.get (13认同)
  • 你还可以使用`$(selector)[0]`吗? (11认同)
  • 凉.但在使用之前,请确保浏览器支持此功能.根据Mozilla"这是一项实验性技术" (3认同)

War*_*ace 44

使用这个简单的脚本

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

如果在url中找到一个哈希标记,则会对该标记进行动画处理.如果未找到哈希标记,则忽略该脚本.


dav*_*rey 32

jQuery(document).ready(function($) {
  $('a[href^="#"]').bind('click.smoothscroll',function (e) {
    e.preventDefault();
    var target = this.hash,
        $target = $(target);

    $('html, body').stop().animate( {
      'scrollTop': $target.offset().top-40
    }, 900, 'swing', function () {
      window.location.hash = target;
    } );
  } );
} );
Run Code Online (Sandbox Code Playgroud)
<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">Section 1</a></li>
  <li id="p2"><a href="#pane2" role="tab">Section 2</a></li>
  <li id="p3"><a href="#pane3" role="tab">Section 3</a></li>
</ul>

<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>
Run Code Online (Sandbox Code Playgroud)


Tej*_*gde 25

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

但在某些情况下,您可能必须将值转换为整数.奇怪的是,返回的值$("...").offset().top有时会在float.
使用:parseInt($("....").offset().top)

例如:

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


Rez*_*dro 19

紧凑版"动画"解决方案.

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

    $('html, body').animate({
        scrollTop: parseInt($(this).offset().top)
    }, speed);
};
Run Code Online (Sandbox Code Playgroud)

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


Ben*_*kes 17

如果您只处理滚动到输入元素,则可以使用focus().例如,如果要滚动到第一个可见输入:

$(':input:visible').first().focus();
Run Code Online (Sandbox Code Playgroud)

或者带有类的容器中的第一个可见输入.error:

$('.error :input:visible').first().focus();
Run Code Online (Sandbox Code Playgroud)

感谢Tricia Ball指出这一点!


Jon*_*han 15

使用此解决方案,您不需要任何插件,除了将脚本放在结束标记之前,无需进行任何设置</body>.

$("a[href^='#']").on("click", function(e) {
  e.preventDefault();
  $("html, body").animate({
    scrollTop: $($(this).attr("href")).offset().top
  }, 1000);
});

if ($(window.location.hash).length > 1) {
  $("html, body").animate({
    scrollTop: $(window.location.hash).offset().top
  }, 1000);
}
Run Code Online (Sandbox Code Playgroud)

在加载时,如果地址中有哈希,我们滚动到它.

并且 - 每当您单击a带有href哈希的链接时#top,我们滚动到它.


obj*_*ect 13

我知道没有jQuery的方法:

document.getElementById("element-id").scrollIntoView();
Run Code Online (Sandbox Code Playgroud)


Edv*_*erg 10

这就是我做到的方式。

document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })
Run Code Online (Sandbox Code Playgroud)

在任何浏览器中均可使用。

它可以很容易地包装成一个函数

function scrollTo(selector) {
    document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })
}
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子

document.querySelector('scrollHere').scrollIntoView({ behavior: 'smooth' })
Run Code Online (Sandbox Code Playgroud)
function scrollTo(selector) {
    document.querySelector(selector).scrollIntoView({ behavior: 'smooth' })
}
Run Code Online (Sandbox Code Playgroud)
$(".btn").click(function() {
  document.getElementById("scrollHere").scrollIntoView( {behavior: "smooth" })
})
Run Code Online (Sandbox Code Playgroud)

文件

  • 很短很甜。需要注意的一件事-我认为这只会将其滚动到视图中(可能在视口的底部),而不是像设置scrollTop一样将其滚动到视口的顶部。 (2认同)

Sha*_*dat 8

$('html, body').animate(...)在 iPhone、Android、Chrome 或 Safari 浏览器中不适用于我。

我必须定位页面的根内容元素。

$('#content').animate(...)

这是我最终得到的结果:

if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
    $('#content').animate({
    scrollTop: $("#elementtoScrollToID").offset().top
   }, 'slow');
}
else{
    $('html, body').animate({
    scrollTop: $("#elementtoScrollToID").offset().top
    }, 'slow');
}
Run Code Online (Sandbox Code Playgroud)

所有正文内容均通过 #content div 连接起来

if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
    $('#content').animate({
    scrollTop: $("#elementtoScrollToID").offset().top
   }, 'slow');
}
else{
    $('html, body').animate({
    scrollTop: $("#elementtoScrollToID").offset().top
    }, 'slow');
}
Run Code Online (Sandbox Code Playgroud)


has*_*nge 7

在大多数情况下,最好使用插件.认真.我要在这里兜售我的.当然还有其他人.但请检查他们是否真的避免了你想要一个插件的陷阱 - 而不是所有的插件.

我已经写过在其他地方使用插件的原因.简而言之,这里的一个衬垫支撑了大多数答案

$('html, body').animate( { scrollTop: $target.offset().top }, duration );
Run Code Online (Sandbox Code Playgroud)

用户体验很糟糕.

  • 动画不响应用户操作.即使用户点击,点击或尝试滚动,它也会继续.

  • 如果动画的起点接近目标元素,则动画非常缓慢.

  • 如果目标元素位于页面底部附近,则无法滚动到窗口顶部.滚动动画然后在中间运动中突然停止.

要处理这些问题(以及其他一些问题),您可以使用我的插件jQuery.scrollable.然后呼叫成为

$( window ).scrollTo( targetPosition );
Run Code Online (Sandbox Code Playgroud)

就是这样.当然,还有更多选择.

关于目标位置,$target.offset().top在大多数情况下是否完成工作.但请注意,返回的值不考虑html元素的边界(请参阅此演示).如果您在任何情况下都需要目标位置准确,最好使用

targetPosition = $( window ).scrollTop() + $target[0].getBoundingClientRect().top;
Run Code Online (Sandbox Code Playgroud)

即使html设置了元素上的边框,这也可以工作.


Vu *_*ung 7

在找到让我的代码工作的方法后,我想我应该把事情说清楚一点:对于使用:

$('html, body').animate({
   scrollTop: $("#div1").offset().top
}, 2000);
Run Code Online (Sandbox Code Playgroud)

您需要位于页面顶部,因为$("#div1").offset().top滚动到的不同位置会返回不同的数字。如果您已经滚动到顶部,则需要指定确切的pageY值(请参阅pageY此处的定义:https : //javascript.info/coordinates)。

所以现在,问题是计算pageY一个元素的值。以下是滚动容器为主体的示例:

function getPageY(id) {
    let elem = document.getElementById(id);
    let box = elem.getBoundingClientRect();
    var body = document.getElementsByTagName("BODY")[0];
    return box.top + body.scrollTop; // for window scroll: box.top + window.scrollY;
}
Run Code Online (Sandbox Code Playgroud)

即使您滚动到某个地方,上述函数也会返回相同的数字。现在,要回滚到该元素:

$("html, body").animate({ scrollTop: getPageY('div1') }, "slow");
Run Code Online (Sandbox Code Playgroud)


Dev*_*vWL 6

非常简单易用的自定义jQuery插件.只需将属性添加scroll=到可点击元素并将其值设置为要滚动到的选择器即可.

像这样:<a scroll="#product">Click me</a>.它可以用在任何元素上.

(function($){
    $.fn.animateScroll = function(){
        console.log($('[scroll]'));
        $('[scroll]').click(function(){
            selector = $($(this).attr('scroll'));
            console.log(selector);
            console.log(selector.offset().top);
            $('html body').animate(
                {scrollTop: (selector.offset().top)}, //- $(window).scrollTop()
                1000
            );
        });
    }
})(jQuery);

// RUN
jQuery(document).ready(function($) {
    $().animateScroll();
});

// IN HTML EXAMPLE
// RUN ONCLICK ON OBJECT WITH ATTRIBUTE SCROLL=".SELECTOR"
// <a scroll="#product">Click To Scroll</a>
Run Code Online (Sandbox Code Playgroud)


FAj*_*jir 6

如果要在溢出容器中滚动(而不是$('html, body')上面的回答),并且还可以使用绝对定位,则可以这样做:

var elem = $('#myElement'),
    container = $('#myScrollableContainer'),
    pos = elem.position().top + container.scrollTop() - container.position().top;

container.animate({
  scrollTop: pos
}
Run Code Online (Sandbox Code Playgroud)


Irs*_*han 6

简单的方法来实现页面滚动到目标div id

var targetOffset = $('#divID').offset().top;
$('html, body').animate({scrollTop: targetOffset}, 1000);
Run Code Online (Sandbox Code Playgroud)


小智 5

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

$(function() {
  // Generic selector to be used anywhere
  $(".js-scroll-to").click(function(e) {

    // Get the href dynamically
    var destination = $(this).attr('href');

    // Prevent href=“#” link from changing the URL hash (optional)
    e.preventDefault();

    // Animate scroll to destination
    $('html, body').animate({
      scrollTop: $(destination).offset().top
    }, 500);
  });
});
Run Code Online (Sandbox Code Playgroud)
<!-- example of a fixed nav menu -->
<ul class="nav">
  <li>
    <a href="#section-1" class="nav-item js-scroll-to">Item 1</a>
  </li>
  <li>
    <a href="#section-2" class="nav-item js-scroll-to">Item 2</a>
  </li>
  <li>
    <a href="#section-3" class="nav-item js-scroll-to">Item 3</a>
  </li>
</ul>
Run Code Online (Sandbox Code Playgroud)


小智 5

动画:

// 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
  });  
});
Run Code Online (Sandbox Code Playgroud)