HTML代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>溢出滚动</title>
<style>
* {
margin: 0;
padding: 0;
}
.body {
width: 300px;
height: 500px;
background: red;
margin: 100px auto;
padding: 20px;
overflow: hidden;
}
.list {
list-style: none;
}
.item {
background: blue;
margin-bottom: 15px;
}
.item:nth-child(1) {
height: 200px;
}
.item:nth-child(2) {
height: 100px;
}
.item:nth-child(3) {
height: 130px;
}
.item:nth-child(4) {
height: 450px;
}
</style>
</head>
<body>
<div class="body">
<ul class="list">
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
</ul>
</div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
</body>
</html>
方法一:getBoundingClientRect()
$(function () {
var $parent = $('.body');
var $list = $('.list');
var $childern = $list.children();
var parentPadding = parseInt($parent.css('padding'));
var parentBottom = Math.abs($parent[0].getBoundingClientRect().bottom);
var listBottom = Math.abs($list[0].getBoundingClientRect().bottom);
for (let i = 0, len = $childern.length; i < len; i++) {
if (Math.abs($childern[i].getBoundingClientRect().bottom) > parentBottom) {
scrollTop($childern.eq(i));
break;
}
}
function scrollTop(el) {
el.on('mouseover', function () {
$parent.animate({ scrollTop: parentPadding + listBottom - parentBottom + 'px'}, 300);
})
}
});
$(function () {
var $parent = $('.body');
var $list = $('.list');
var $childern = $list.children();
var parentPadding = parseInt($parent.css('padding'));
var itemBottom = parseInt($childern.css('margin-bottom'));
var parentHeight = $parent[0].offsetHeight;
var listHeight = $list[0].offsetHeight;
for (let i = 0, len = $childern.length, sum = 0; i < len; i++) {
sum += $childern[i].offsetHeight + itemBottom;
if (listHeight - sum < listHeight - parentHeight + parentPadding * 2) {
scrollTop($childern.eq(i));
break;
}
}
function scrollTop(el) {
el.on('mouseover', function () {
$parent.animate({ scrollTop: (listHeight - parentHeight + parentPadding * 2) + 'px'}, 300);
})
}
});