我的html代码中有两个可滚动的列表,我希望两个列表在垂直方向上向相反方向滚动,这意味着当我向上滚动一个列表时,另一个列表应该自动向下滚动,因为我正在做类似的事情但这不起作用,请帮助...
<script>
// Add event listener for scrolling
$("#list1").on("scroll", function () {
var scrolledleft = parseInt($("#list1").scrollTop()) * -1;
console.log(scrolledleft + scrolledright)
$("#list2").scrollTop(scrolledleft + scrolledright);
})
//Move right column to bottom initially
$("#list2").scrollTop($("#list2").height());
//Get actual distance scrolled
var scrolledright = parseInt($("#list2").scrollTop());
</script>
答案 0 :(得分:2)
这是一个小提琴 - https://jsfiddle.net/xc286hw1/1/
基本上,@ Dr.AaronDishno在他的评论中提到了
$(document).ready( function() {
// Default 2nd list to bottom
$('#list2').scrollTop($('#list2')[0].scrollHeight);
// Get scrollable height for both lists
var list1Height = $('#list1')[0].scrollHeight;
var list2Height = $('#list2')[0].scrollHeight;
// When list 1 is scrolled....
$('#list1').scroll( function() {
// Calculate current offset % for list1 (being scrolled by user)
// and new offset % for list2 (scroll position adjusted with this script)
var list1Offset = ( $(this).scrollTop() + $(this).height() ) / list1Height;
var list2Offset = 1 - list1Offset;
var list2Position = list2Height * list2Offset;
// Set new scroll position for list2
$('#list2').scrollTop(list2Position);
});
});
&#13;
#list1,
#list2 {
height: 100px;
width: 40%;
display: inline-block;
border: 1px solid #000;
background: #FFF;
overflow-y: scroll;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="list1">
<ul>
<li>a</li>
<li>y</li>
<li>y</li>
<li>l</li>
<li>m</li>
<li>a</li>
<li>o</li>
<li>!</li>
</ul>
</div>
<div id="list2">
<ul>
<li>a</li>
<li>y</li>
<li>y</li>
<li>l</li>
<li>m</li>
<li>a</li>
<li>o</li>
<li>!</li>
</ul>
</div>
&#13;