【问题标题】:jquery get .offset value of a variable(element) then animate to itjquery 获取变量(元素)的 .offset 值,然后对其进行动画处理
【发布时间】:2015-03-11 01:31:03
【问题描述】:

我有一个简单的导航。

<nav>
    <a href="#section1">page 1</a>
    <a href="#section2">page 2</a>
    <a href="#section3">page 3</a>
</nav>

当用户单击其中一个链接时,我希望页面动画到页面上的相应部分。

我似乎无法从变量中获取 .offset().top 值。任何帮助将不胜感激。

$("nav a").click(function(e) {
    e.preventDefault();
    // figure out which button was clicked
    var targetName = $(this).attr("href");
    // get the current position of the target element
    var targetOffset = targetName.offset().top;
    // send the page there
    $("html, body").animate({
        top: targetOffset
    });
});

【问题讨论】:

    标签: jquery jquery-animate offset var


    【解决方案1】:

    问题是targetName 不是 jQuery 对象,在您的控制台中您应该会看到类似 Uncaught TypeError: undefined is not a function 的错误

    $("nav a").click(function(e) {
        e.preventDefault();
        // figure out which button was clicked
        var targetName = $(this).attr("href");
        // get the current position of the target element
        var targetOffset = $(targetName).offset().top; //targetName is not  jQuery object
        // send the page there
        $("html, body").animate({
            scrollTop: targetOffset //also use scrollTop to animate scrolling
        });
    });
    

    演示:Fiddle

    【讨论】:

    • 谢谢阿伦!完美运行!
    【解决方案2】:

    您需要设置适当的对象以像 Arun 所说的那样设置动画,我错了 - 没有想清楚:)

       $("nav a").click(function(e) {
            e.preventDefault();
            // figure out which button was clicked
            var targetName = $(this).attr("href");
            // get the current position of the target element
            var targetOffset = $(targetName).offset().top;
            // send the page there
            $("html, body").animate({
                scrollTop: targetOffset
            }, 1400);
        });
    

    示例JSFIDDLE

    【讨论】:

      猜你喜欢
      • 2016-12-18
      • 1970-01-01
      • 2016-01-21
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2013-11-15
      • 2012-06-13
      • 2015-10-07
      相关资源
      最近更新 更多