javascript實現(xiàn)滾動條效果
更新時間:2020年03月24日 09:33:51 作者:zhanghe-V
這篇文章主要為大家詳細介紹了javascript實現(xiàn)滾動條效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了javascript實現(xiàn)滾動條效果的具體代碼,供大家參考,具體內(nèi)容如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
html, body {
height: 100%;
margin: 0;
}
#container {
position: absolute;
top: 50px;
left: 100px;
height: 400px;
width: 150px;
background-color: aliceblue;
padding: 2rem;
box-sizing: border-box;
/*必須屬性,否則給scrollTop賦值無效*/
overflow-y: hidden;
position: relative;
padding-right: 30px;
}
.scrollbar {
height: 50px;
width: 10px;
border-radius: 20px;
background: #ccc;
position: absolute;
right: 0;
}
</style>
<script>
window.onload = function () {
var scrollbar = document.querySelector('.scrollbar');
var container = scrollbar.parentNode;
container.scrollbar = scrollbar;
container.ratio =
(container.scrollHeight - container.offsetHeight) / (container.offsetHeight - scrollbar.offsetHeight);
container.addEventListener('mousewheel', function(e) {
this.scrollTop += e.deltaY;
this.scrollbar.style.top = (this.scrollTop + this.scrollTop / this.ratio) + 'px';
});
container.addEventListener('mousedown', function (e) {
if (e.target === this.scrollbar) {
this.prevY = e.pageY;
}
});
container.addEventListener('mouseup', function (e) {
this.prevY = null;
});
container.addEventListener('mousemove', function (e) {
if (this.prevY) {
this.scrollTop += (e.pageY - this.prevY) * this.ratio;
this.scrollbar.style.top = (this.scrollTop + this.scrollTop / this.ratio) + 'px';
this.prevY = e.pageY;
}
e.preventDefault();
});
}
</script>
</head>
<body>
<div id="container">
<div class="scrollbar"></div>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
<p>fefe</p>
</div>
</body>
</html>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Javascript實現(xiàn)鼠標(biāo)移入方向感知
這篇文章主要為大家詳細介紹了Javascript實現(xiàn)鼠標(biāo)移入方向感知,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-06-06
JavaScript文件的同步和異步加載的實現(xiàn)代碼
本篇文章主要介紹了JavaScript文件的同步和異步加載的實現(xiàn)代碼,具有一定的參考價值,有興趣的可以了解一下2017-08-08
微信小程序?qū)崿F(xiàn)基于三元運算驗證手機號/姓名功能示例
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)基于三元運算驗證手機號/姓名功能,涉及三元運算符的判定及字符串正則驗證相關(guān)操作技巧,需要的朋友可以參考下2019-01-01
JS如何實現(xiàn)Base64編碼和解碼(及中文亂碼問題)
這篇文章主要給大家介紹了關(guān)于JS如何實現(xiàn)Base64編碼和解碼及中文亂碼問題的相關(guān)資料,Base64編碼是一種常用的將二進制數(shù)據(jù)轉(zhuǎn)換為文本數(shù)據(jù)的方式,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-10-10
JS中的Error對象及使用JSON.stringify()序列化Error問題
這篇文章主要介紹了JS中的Error對象及使用JSON.stringify()序列化Error問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08

