javascript實(shí)現(xiàn)滾動條效果
更新時(shí)間:2020年03月24日 09:33:51 作者:zhanghe-V
這篇文章主要為大家詳細(xì)介紹了javascript實(shí)現(xiàn)滾動條效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了javascript實(shí)現(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)文章
jQuery實(shí)現(xiàn)可收縮展開的級聯(lián)菜單實(shí)例代碼
這篇文章主要是對利用jQuery實(shí)現(xiàn)可收縮展開的級聯(lián)菜單的實(shí)例代碼進(jìn)行了詳細(xì)的介紹,需要的朋友可以過來參考下,希望對大家有所幫助2013-11-11
Javascript取整函數(shù)及向零取整幾種常用的方法
這篇文章主要介紹了Javascript取整函數(shù)及向零取整幾種常用的方法,每種方法都有其特點(diǎn)和適用場景,推薦使用Math.trunc(),因?yàn)樗Z義明確、代碼易讀且性能較好,需要的朋友可以參考下2025-01-01
js實(shí)現(xiàn)簡單的隨機(jī)點(diǎn)名器
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)簡單的隨機(jī)點(diǎn)名器,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-09-09

