我需要回滚到用户最初单击的位置。以下是一系列动作
尽管我能够将用户带到原始位置,但有时所选项目始终一直滚动到顶部。它应该滚动到用户单击的确切位置。谢谢!
$('li').each(function() {
$(this).on("click", function() {
$(this).addClass('active');
var pos = $(this).offset().top;
$(this).attr('data-scrollpos', pos);
});
});
$('#back').click(function() {
$("html, body").animate({
scrollTop: 0
}, 600);
});
$('#activePos').click(function() {
var pos1 = $('li.active').attr('data-scrollpos');
$("html, body").animate({
scrollTop: pos1
}, 600);
});
ul {
padding: 0;
margin: 0;
display: flex;
list-style: none;
flex-wrap: wrap;
}
li {
border: solid 1px #CCC;
width: 48%;
height: 300px;
width: 300px;
}
.active {
border: solid 1px orange;
}
div {
position: fixed;
top: 0;
right: 0;
}
span {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li>Eight</li>
</ul>
<div>
<span id="back">Scroll to Top</span>
<span id="activePos">Back to Active</span>
<span id="position"></span>
</div>
答案 0 :(得分:0)
您需要的是以下行:
$(".active").removeClass("active");
设置活动班级时,在其他人上禁用活动班级。
$('li').each(function() {
$(this).on("click", function() {
$(".active").removeClass("active");
$(this).addClass('active');
var pos = $(this).offset().top;
$(this).attr('data-scrollpos', pos);
});
});
$('#back').click(function() {
$("html, body").animate({
scrollTop: 0
}, 600);
});
$('#activePos').click(function() {
var pos1 = $('li.active').attr('data-scrollpos');
$("html, body").animate({
scrollTop: pos1
}, 600);
});
ul {
padding: 0;
margin: 0;
display: flex;
list-style: none;
flex-wrap: wrap;
}
li {
border: solid 1px #CCC;
width: 48%;
height: 300px;
width: 300px;
}
.active {
border: solid 1px orange;
}
div {
position: fixed;
top: 0;
right: 0;
}
span {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li>Eight</li>
</ul>
<div>
<span id="back">Scroll to Top</span>
<span id="activePos">Back to Active</span>
<span id="position"></span>
</div>