javascript - jQuery平滑滚动 anchor 问题

标签 javascript jquery html css

我是 jQuery 的新手,正在尝试实现平滑滚动到我的 Web 元素中的 div。出于某种原因,当我创建一个新的基本 html 测试页面并添加用于滚动的 js 时,它起作用了。但是,当我将完全相同的代码导入到我的主元素中时,它实际上并没有滚动,而是在稍作停顿后直接跳转到预期的 div。我不知道为什么它会在测试页面上运行而不是在我的实际元素中运行。有没有人知道什么会导致它这样做?任何帮助将非常感激!谢谢。

我在头部定义了以下脚本:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script src="js/script.js"></script>

HTML:

<div id="mainContent">
    <section id="splash">
        <div class="banner">

        </div>

        <div id="intro">
            <h1>Heading 1</h1>
            <h2>Heading 2</h2>
            <a href="#productInfo">LEARN MORE</a>
        </div>

    </section>

    <div id="productInfo">
            </div>

在 script.js 中:

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash,
    $target = $(target);

    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;
    });
});
});

最佳答案

fiddle 中完成

下面是代码,

HTML:

<section id="splash">
    <div class="banner"></div>
    <div id="mainContent">
        <div id="intro">
            <h1>Heading 1</h1>
            <h2>Heading 2</h2>
            <a href="#productInfo">LEARN MORE</a>
        </div>
    </div>
</section>
<div id="productInfo">test tests</div>

CSS:

#productInfo { background:gray; color:#000; margin-top:400px; padding:10px; height:1000px;}

jQuery:

$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
    e.preventDefault();

    var target = this.hash,
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top
    }, 900, 'swing', function () {
        window.location.hash = target;

    });
});
});

关于javascript - jQuery平滑滚动 anchor 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22044173/

相关文章:

javascript - 使用 Javascript 从 Sharepoint 列表的 ListView 中检索项目

javascript - 带和不带 sleep 的递归异步

jquery mobile Accordion 不工作(不显示)

javascript - 如何从 AlloyUI 表单生成器中提取结构?

javascript - 如何对包含表示分数的数组的多个对象进行排序?

javascript - 取消或停止递归 promise 链中的 $timeout

javascript - ChartJS——当我必须缩放时如何更改刻度颜色?

javascript - w2ui 网格中具有多个文本行的单元格

html - 打印网页时的不同结果

html - CSS边距连接?