jquery - 滚动 jquery 动画缺少 div

标签 jquery css animation scroll

我有一个指向“第 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>

最佳答案

原因似乎是 $(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。”:

JavaScript has a mechanism that tries to correct faulty programs by automatically inserting semicolons. Do not depend on this. It can mask more serious errors. It sometimes inserts semicolons in places where they are not welcome. Consider the consequences of semicolon insertion on the return statement. If a return statement returns a value, that value expression must begin on the same line as the return:

关于jquery - 滚动 jquery 动画缺少 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17081937/

相关文章:

jquery - 动画 SVG 在页面加载之前不会动画

ios - 如何在 Xamarin(iOS) 中将按钮从右移到左

javascript - 为什么可以链接 jquery 效果,而不是使用回调

javascript - jquery - 单击事件绑定(bind)并在页面加载时启动

javascript - 下拉菜单隐藏在 iframe 后面

php - 这需要如何解析 JSON?

c# - 中继点击按钮触发 ASP.NET 文件上传

html - 无法减少图像和段落之间的额外空间

javascript - Jquery .html 不起作用

javascript - AJAX 从选定的下拉列表中获取数据并给出结果 PHP