我是 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/