javascript模拟实现滚动条效果代码实例

快乐打工仔 分类:实例代码

很多时候,自带的滚动条并不能够满足我们的需求。

多半是由于丑陋的外观导致的,下面就分享一段代码实例,它模拟实现了垂直滚动条效果。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>犀牛前端部落</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
background: #E5F0FF;
}
.wrap {
width: 520px;
height: 500px;
margin: 50px auto;
overflow: hidden;
border: 1px solid #999;
border-radius: 5px;
background: #fff;
position: relative;
-moz-user-select: none;
}
.content {
float: left;
width: 480px;
padding: 10px;
position: absolute;
top: 0;
}
.scrollbar {
float: right;
width: 20px;
background: #ececec;
height: 500px;
position: relative;
}
.bar {
width: 20px;
height: 50px;
border: 1px solid #bbb;
background: #ccc;
border-radius: 5px;
cursor: default;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div class="wrap">
<div class="content"></div>
<div class="scrollbar">
<div class="bar"></div>
</div>
</div>
<script>
(function () {
var wrap = document.querySelector('.wrap');
var content = document.querySelector('.content');
var scrollbar = document.querySelector('.scrollbar')
var bar = document.querySelector('.bar');
var scrollbarPos = pos(scrollbar);
var wrapPos = pos(wrap);
var flag = false;
function pos(ele) {
return ele.getBoundingClientRect();
}
bar.onmousedown = function (e) {
var e = e || window.event;
var barPos = pos(bar);
var mouseY = e.clientY - barPos.top;
flag = true;
document.onmousemove = function (e) {
if (flag) {
var e = e || window.event;
var contentPos = pos(content);
var Y = e.clientY - mouseY - scrollbarPos.top;
if (Y < 0) {
Y = 0;
}
else if (Y > scrollbarPos.height - barPos.height) {
Y = scrollbarPos.height - barPos.height;
}
var cY = -Y * (contentPos.height - wrapPos.height) / (scrollbarPos.height - barPos.height);
bar.style.top = Y + 'px';
content.style.top = cY + 'px';
}
return false;
}
document.onmouseup = function () {
flag = false;
document.onmousemove = null;
}
}
wrap.onselectstart = function () {
return false;
}
if (wrap.onmousewheel === null) {
wrap.onmousewheel = function (e) {
var e = e || window.event;
var delta = event.wheelDelta;
fn(delta);
}
}
else {
wrap.addEventListener('DOMMouseScroll', function (e) {
var delta = e.detail > 0 ? -120 : 120;
e.preventDefault();
fn(delta);
}, false)
}
function fn(delta) {
var contentY = pos(content).top - wrapPos.top;
var cY = contentY + delta;
if (cY >= 0) {
cY = 0;
}
else if (cY <= -pos(content).height + wrapPos.height) {
cY = -pos(content).height + wrapPos.height;
}
var bY = -cY * (scrollbarPos.height - pos(bar).height) / (pos(content).height - wrapPos.height)
bar.style.top = bY + 'px';
content.style.top = cY + 'px';
}
})()
</script>
</body>
</html>

javascript模拟实现滚动条效果代码实例,这样的场景在实际项目中还是用的比较多的,关于javascript模拟实现滚动条效果代码实例就介绍到这了。

javascript模拟实现滚动条效果代码实例属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容