我尝试使用scrollTop, 当用户单击( li )元素时,我从( li )获取( data-id )并滚动到旁边的框中拥有相同的身份;
问题是当我点击例如( li )数字2时,每件事情都很好但是当我再次点击它时,滚动回到顶部,如果你快速点击它会变得最糟糕
var aside = $('.aside');
$("li").on('click',function (){
id = $(this).data("id")
$('.aside').animate({
scrollTop: $('div.item[data-id="' + id + '"]').offset().top
}, 300, 'linear')
});
html,body {
width: 100%;
height: 100%;
float: right;
margin:0;
padding: 0;
}
.aside {
height: 100%;
width: 400px;
position: fixed;
top: 0;
right:0;
background: #ccc;
overflow-y: scroll;
}
.estateWrap {
width: 100%;
height: 100%;
float: right;
margin: 0;
padding: 0;
}
.item {
float: right;
margin: 0px;
padding:0px;
width: 100%;
height: 150px;
background: #f5f5f5;
margin-bottom: 100px
}
<html>
<head>
<meta charset="UTF-8">
<title> index </title>
<script src="jQuery.min.js"></script>
</head>
<body>
<ul>
<li data-id="1">1</li>
<li data-id="2">2</li>
<li data-id="3">3</li>
<li data-id="4">4</li>
</ul>
<div class="aside">
<div class="estateWrap">
<div class="item" data-id="1">1</div>
<div class="item" data-id="2">2</div>
<div class="item" data-id="3">3</div>
<div class="item" data-id="4">4</div>
</div>
</div>
</body>
</html>
答案 0 :(得分:1)
您需要考虑item
元素的偏移顶部位置在滚动后发生更改。最高值变为0
。这就是为什么在您再次点击同一链接后,它将一直向0
。
您可以添加父项旁边元素的当前顶部位置,如下所示:
var aside = $('.aside');
function scrollAside (topPos) {
aside.animate({
scrollTop: topPos
}, 300, 'linear')
}
$("li").on('click',function () {
var id = $(this).data("id"),
crntScrollPos = aside.scrollTop(),
top = $('div.item[data-id="' + id + '"]').offset().top;
if (top + crntScrollPos !== crntScrollPos) {
scrollAside(top + crntScrollPos);
}
});
html,body {
width: 100%;
height: 100%;
float: right;
margin:0;
padding: 0;
}
.aside {
height: 100%;
width: 400px;
position: fixed;
top: 0;
right:0;
background: #ccc;
overflow-y: scroll;
}
.estateWrap {
width: 100%;
height: 100%;
float: right;
margin: 0;
padding: 0;
}
.item {
float: right;
margin: 0px;
padding:0px;
width: 100%;
height: 150px;
background: #f5f5f5;
margin-bottom: 100px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
<li data-id="1">1</li>
<li data-id="2">2</li>
<li data-id="3">3</li>
<li data-id="4">4</li>
</ul>
<div class="aside">
<div class="estateWrap">
<div class="item" data-id="1">1</div>
<div class="item" data-id="2">2</div>
<div class="item" data-id="3">3</div>
<div class="item" data-id="4">4</div>
</div>
</div>
答案 1 :(得分:0)
使用position而不是offset:
position();
获取匹配元素集中第一个元素的当前坐标,相对于偏移父元素。