【问题标题】:Scroll jquery animation missing div滚动 jquery 动画缺少 div
【发布时间】:2013-06-09 12:51:27
【问题描述】:

我有一个指向“第 2 步”的滚动动画,但动画一直到“第 3 步”。尽管我到第 3 步的链接似乎可以使用相同的功能。 我不明白为什么它没有停在正确的 div 上,感谢您的帮助!

这是我的代码:

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.out{background:gray;height:300px;}
.box{height:300px;overflow:auto;}
.question1{background:red;height:300px;}
.question2{background:green;height:300px;}
.question3{background:blue;height:300px;}
.question4{background:yellow;height:300px;}
</style>
</head>

<body>
<div class="out">
    here
</div>
<div class="box">
    <div class="question1" id="step1"> 
        step 1<br>
        <a href="#step2">Step 2</a>
    </div>
    <div class="question2" id="step2">
        step 2<br>
        <a href="#step3">step 3</a>
    </div>
    <div class="question3" id="step3">
        step 3
    </div>
    <div class="question4" id="step4">
        step 4
    </div>
</div>
<div class="out">
    here
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function(){

    $('a[href^="#"]').click(function(){  
        var the_id = $(this).attr("href");  
        $('.box').animate({  
            scrollTop:$(the_id).offset().top  
        }, 'slow');  
        return false;  
    });  

});
</script>
</html>

【问题讨论】:

    标签: jquery css animation scroll


    【解决方案1】:

    您错误地放置了 div 和锚点!

    另外,根据您定位 html 的方式,您可以尝试使用 $(the_id).position().top + 'px'

    .position() 获取与父级边界相关的偏移量,而 offset() 使用文档的边界。

    【讨论】:

    【解决方案2】:

    原因似乎是 $(the_id).position().top 后面缺少分号;我将您的代码放入 jsfiddle 中,现在在 ie 和 firefox 中对我来说效果很好:http://jsfiddle.net/HZTDE/1/

    scrollTop:$(the_id).offset().top;
    

    这可能与自动分号插入有关 - 引用自 “JavaScript:Douglas Crockford 的优秀部分。版权所有 2008 Yahoo! Inc.,978-0-596-51774-8。” em>:

    JavaScript 有一种通过自动插入分号来尝试纠正错误程序的机制。不要依赖于此。它可以掩盖更严重的错误。它有时会在不受欢迎的地方插入分号。考虑在 return 语句中插入分号的后果。如果 return 语句返回一个值,则该值表达式必须与 return 在同一行开始:

    【讨论】:

    • 你知道如何保存动画吗?
    • 你是对的,如果没有分号,它似乎会动态重新计算偏移量,因此作为一个建议,这是一个适用于 Firefox 的改编版本,即(尚未尝试过其他版本);基本上这个想法是在加载时保存原始偏移量; jsfiddle.net/HZTDE/3
    • 那太好了,我的朋友,正是我需要的,谢谢!愿原力与你同在!
    猜你喜欢
    • 2011-12-30
    • 2015-12-16
    • 2013-04-04
    • 1970-01-01
    • 2016-05-11
    • 2023-03-23
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多