如何使用jQuery在水平滚动容器中查找元素的左侧位置?
要使用jQuery在水平滚动容器中查找元素的左侧位置,请将该animate()函数与函数一起使用scrollLeft()。
示例
您可以尝试运行以下代码,以了解如何在水平滚动容器中查找元素的左侧位置:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var scrollArea = $('#box');
var toScroll = $('#box .myclass');
function myScroll() {
toScroll.each(function() {
var self = $(this);
$(this).css('cursor', 'pointer');
$(this).on('click', function () {
var leftOffset = self.offset().left - scrollArea.offset().left + scrollArea.scrollLeft();
scrollArea.animate({ scrollLeft: leftOffset });
alert(leftOffset);
});
});
};
myScroll();
});
</script>
<style>
#box {
width: 250px;
height: 300px;
margin-left: 20px;
border: 1px solid black;
overflow-x: scroll;
white-space: nowrap;
}
.myclass {
width: 250px;
height: 100px;
margin: 35px;
display: inline-block;
background: -webkit-linear-gradient(left, red , blue);
background: -o-linear-gradient(right, red, blue);
background: -moz-linear-gradient(right, red, blue);
background: linear-gradient(to right, red , blue);
}
</style>
</head>
<body>
<p>Get left position of element.</p>
<div id="box">
<div class="myclass">First (Click Me)</div>
<div class="myclass">Second (Click Me)</div>
<div class="myclass">Third (Click Me)</div>
</div>
</body>
</html>热门推荐
10 情侣祝福语古文简短独特
11 酒店伴娘祝福语简短
12 晚上甜蜜的祝福语简短
13 给新娘简短的祝福语
14 当爸爸的简短祝福语
15 洛宁新年祝福语大全简短
16 新年祝福语简短搞笑幽默
17 结婚祝福语大全简短霸气
18 新人结婚祝福语简短高端