只需单击并使用 anchor 滚动到 div。在您单击其他按钮之前,第一个按钮似乎工作正常。单击第二个链接后,它不会滚动,而只会向下滚动几个像素。如果您开始随机按下它们,它只会变成乱七八糟的随机滚动到任何地方。
这是我做的一支笔:
https://codepen.io/sergestra/pen/pMrdzp
jQuery.noConflict();
jQuery(document).ready(function($) {
$('[data-anchor]').click(function() {
var target = $($(this).data('anchor'));
if (target.length) {
$('.right').animate({
scrollTop: target.offset().top
}, 1000);
}
});
});
* {
padding: 0;
margin: 0;
}
html,
body {
width: 100%;
height: 100%;
}
ul {
list-style: none;
}
li {
font-size: 2rem;
padding: 20px 0;
cursor: pointer;
}
li:hover {
color: white;
}
.wrapper {
width: 100%;
height: 100%;
}
.left {
float: left;
width: 20%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: rgba(0, 0, 0, 0.2);
}
.colors {
font-size: 2rem;
padding: 20px 0;
cursor: pointer;
}
.colors:hover {
color: white;
}
.right {
float: left;
width: 80%;
height: 100%;
overflow: auto;
}
.right div {
display: flex;
align-items: center;
height: 200px;
background-color: rgba(0, 0, 0, 0.4);
padding: 20px;
border: 2px solid white;
color: white;
font-size: 2rem;
}
#blue {
background-color: blue;
}
#green {
background-color: green;
}
#yellow {
background-color: yellow;
}
#red {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="left">
<div>
<div class="colors" data-anchor="#blue">GO TO BLUE</div>
<div class="colors" data-anchor="#green">GO TO GREEN</div>
<div class="colors" data-anchor="#yellow">GO TO YELLOW</div>
<div class="colors" data-anchor="#red">GO TO RED</div>
</div>
</div>
<div class="right">
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div id="blue">blue</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div id="green">green</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div id="yellow">yellow</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div id="red">red</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
<div>gray</div>
</div>
</div>
我已经尝试重新排列我的 css 和 html,但它似乎对解决问题没有帮助。 它应该只是滚动到我调用的任何 div,但它随机滚动。
最佳答案
只需进行以下更改。 https://codepen.io/anon/pen/MNvGgR
$('.right').animate({
scrollTop: target[0].offsetTop
}, 1000);
关于javascript - jQuery [data-anchor] 似乎出现故障,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57321161/