jQuery中的scrollTo函数无法工作

28

我需要使jQuery的scrollTo函数在这个网站上工作:http://cinicraft.com/Silverman/index.html

我尝试了以下方法:

$(document).ready(function()
{
    $("div.btnLp3").click(function(){
        $('body,html').scrollTo('#target-examples', 800, {easing:'elasout'});
    });
});

我也尝试过这个:

$(document).ready(function()
{
    $("div.btnLp3").click(function(){
        $('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
    });
});

我似乎无法让 scrollTo 正常工作。有人有什么想法吗?这是我导入的代码:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">  </script>    
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js">  </script>
3个回答

53

试试这个

$("#clickme").click(function() {
    $('html, body').animate({
        scrollTop: $("#wrap2").offset().top
    }, 2000);
    return false;
});

FIDDLE


(翻译:)

3
我喜欢加入一些偏移量,这样可以在内容周围为观众留出一些空间。就像这样.offset().top - 20} - user2898276
4
这并没有回答为什么用户会收到“scrollTo不是一个函数”的错误提示,大多数人会在搜索“scrollTo不是一个函数”后找到这个问题。而您的回答中甚至没有使用涉及到的'scrollTo'函数。使用完全不同的函数如何回答为什么操作员在“scrollTo”上出现错误的问题呢? - user8588978

4
/*
* ScrollToElement 1.0
* Copyright (c) 2009 Lauri Huovila, Neovica Oy
*  lauri.huovila@neovica.fi
*  http://www.neovica.fi
*  
* Dual licensed under the MIT and GPL licenses.
*/

(function($) {
    $.scrollToElement = function($element, speed) {

        speed = speed || 750;

        $("html, body").animate({
            scrollTop: $element.offset().top,
            scrollLeft: $element.offset().left
        }, speed);
        return $element;
    };

    $.fn.scrollTo = function(speed) {
        speed = speed || "normal";
        return $.scrollToElement(this, speed);
    };
})(jQuery);

1
 $("#your-div")[0].scrollTo(0, Number.MAX_SAFE_INTEGER);

4
虽然这段代码可能解决问题,但一个好的答案也应该解释它是如何起作用并且它如何帮助解决问题。 - Suraj Kumar
抱歉,首先我找到将受滚动影响的目标元素(在这种情况下,我使用jQuery通过ID查找元素)。然后我使用scrollTo()函数 https://www.w3schools.com/jsref/met_win_scrollto.asp - grecio beline

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接