我有一个 html 页面,我想让它缓慢滚动到页面的特定点或整个页面。我尝试了以下代码,但没有任何效果:
<a href="#anchorName"></a>
<script>
function scrollTo(hash)
{
location.hash = "#anchorName";
}
</script>
其次,我尝试滚动到 div,但在这种情况下我还必须使用 CSS 并设置高度。我正在努力避免这种情况。
如 stackoverflow 过去的问题所示:
<a href="#myDiv" id="button">button</a>
<script>
$("#button").click(function()
{
$('html, body').animate({
scrollTop: $("#myDiv").offset().top
}, 2000);
});
</script>
而且它根本不起作用。
尝试这样:
$(document).ready(function(){
$("#button").click(function(e) {
e.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 2000);
});
});
#myDiv {
margin-top: 800px;
height: 50px;
width: 300px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a href="#myDiv" id="button">button</a>
<div id="myDiv"></div>
由于您将
#myDiv
设置为按钮的 href,因此您必须在触发动画之前 preventDefault():
$("#button").click(function(e){
e.preventDefault();
$('html, body').animate({
scrollTop: $("#myDiv").offset().top
}, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="myDiv" id="button">button</a>
<div style="height:400px;"></div>
<div id="myDiv">Lorem Ipsum</div>
如果您使用的是 css 文件,可以插入以下规则 缓慢滚动...
html {
scroll-behavior: smooth;
}
您可以按照使用 jQuery 的示例代码平滑滚动到某个组件 id,例如:
<a class="move_to_div" href="#anchorName"> move div </a>
<div id="anchorName"> </div>
<script>
$(".move_to_div").click(function() {
$('html, body').animate({
scrollTop: $("#anchorName").offset().top
}, 1000);
});
</script>
这只是示例,当单击“a href 链接”时,向下滚动将会平滑(要测试结果,请使用 css 在链接和 div 之间添加一些空格) 我希望这对你有帮助。