jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。滚动条是网页元素(如 div、textarea 等)的一部分,允许用户通过滚动查看内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>原生滚动条示例</title>
<style>
.scrollable {
width: 300px;
height: 200px;
overflow: auto;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="scrollable">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>自定义滚动条示例</title>
<style>
.scrollable {
width: 300px;
height: 200px;
overflow: hidden;
position: relative;
}
.scrollable .content {
width: 100%;
height: auto;
overflow-y: scroll;
padding-right: 20px; /* 留出滚动条的空间 */
}
.scrollable .scrollbar {
width: 10px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
background: #ddd;
}
.scrollable .scrollbar .thumb {
width: 100%;
background: #888;
position: absolute;
cursor: pointer;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="scrollable">
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div class="scrollbar">
<div class="thumb"></div>
</div>
</div>
<script>
$(document).ready(function() {
var $content = $('.scrollable .content');
var $thumb = $('.scrollable .scrollbar .thumb');
var thumbHeight = ($('.scrollable').height() / $content.height()) * $('.scrollable').height();
$thumb.css('height', thumbHeight);
$content.on('scroll', function() {
var scrollPercent = $content.scrollTop() / ($content.height() - $('.scrollable').height());
$thumb.css('top', scrollPercent * ($('.scrollable').height() - thumbHeight));
});
$thumb.on('mousedown', function(event) {
var startY = event.clientY;
$(document).on('mousemove', function(event) {
var moveY = event.clientY;
var newScrollTop = (moveY - startY) / ($('.scrollable').height() - thumbHeight) * ($content.height() - $('.scrollable').height());
$content.scrollTop(newScrollTop);
});
$(document).on('mouseup', function() {
$(document).off('mousemove');
$(document).off('mouseup');
});
});
});
</script>
</body>
</html>
overflow
属性设置为 visible
。overflow
属性设置为 auto
或 scroll
。通过以上内容,你应该对 jQuery 滚动条有了全面的了解,并能够解决常见的滚动条问题。
领取专属 10元无门槛券
手把手带您无忧上云