gpt4 book ai didi

javascript - jQuery scrollTop - 哈希值错误的问题

转载 作者:行者123 更新时间:2023-11-30 10:05:23 25 4
gpt4 key购买 nike

我正在尝试对位于全屏内部的 anchor 执行 scrollTop 动画 <section> ,但在第一次点击时不会滚动到右侧 anchor 。这是我的代码。

<nav id="scroller"> <a href="#subBox1">Scroll me to sub 1</a>
<a href="#subBox2">Scroll me to sub 2</a>
<a href="#subBox3">Scroll me to sub 3</a>

</nav>
<section id="boxTop"></section>
<section id="boxMaster">
<section id="subBox1">
<p>Hello. I am the Sub 1!</p>
</section>
<section id="subBox2">
<p>Hello. I am the Sub 2!</p>
</section>
<section id="subBox3">
<p>Hello. I am the Sub 3!</p>
</section>
</section>

$("#scroller a").click(function () {
$('#boxMaster').animate({
scrollTop: $(this.hash).offset().top
}, 700);
$("#scroller a").removeClass("active");
$(this).addClass("active");
});

fiddle

$("#scroller a").click(function() {
$('#boxMaster').animate({
scrollTop: $(this.hash).offset().top
}, 700);
$("#scroller a").removeClass("active");
$(this).addClass("active");
});
html,
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#scroller {
position: fixed;
top: 0;
height: 30px;
text-align: center;
}
#scroller a {
color: #fff;
margin: 0 20px;
text-decoration: none;
}
#scroller a.active {
font-weight: bold;
text-decoration: underline;
}
#boxTop {
width: 100%;
height: 100%;
background: red;
}
#boxMaster {
width: 100%;
height: 100%;
background: blue;
overflow: hidden;
}
#boxMaster #subBox1,
#boxMaster #subBox2,
#boxMaster #subBox3 {
width: 100%;
height: 100%;
display: table;
}
p {
color: #fff;
text-align: center;
display: table-cell;
vertical-align: middle;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="scroller"> <a href="#subBox1">Scroll me to sub 1</a>
<a href="#subBox2">Scroll me to sub 2</a>
<a href="#subBox3">Scroll me to sub 3</a>

</nav>
<section id="boxTop"></section>
<section id="boxMaster">
<section id="subBox1">
<p>Hello. I am the Sub 1!</p>
</section>
<section id="subBox2">
<p>Hello. I am the Sub 2!</p>
</section>
<section id="subBox3">
<p>Hello. I am the Sub 3!</p>
</section>
</section>

最佳答案

将当前滚动条值添加到 offset().top() 中,后者相对于框架的顶部,并删除 this.hash。请改用 this.href

$("#scroller a").click(function () {
var y=$('#boxMaster').scrollTop()
$('#boxMaster').animate({
scrollTop: $(this.href).offset().top + y
}, 100);
});

关于javascript - jQuery scrollTop - 哈希值错误的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29450077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com