这篇文章为大家详细主要介绍了 JavaScript 实现垂直滚动条效果的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
1、红色盒子高度计算公式:
容器的高度 / 内容的高度 * 容器的高度
2、红色方块移动一像素 ,我们的内容盒子移动多少呢?
(内容盒子高度 - 大盒子高度) / (大盒子高度 - 红色盒子的高度) 计算倍数
(内容盒子高度 - 大盒子高度)/ (大盒子高度 - 红色盒子的高度) * 红色盒子移动的数值
- <html>
- <head>
- <meta charset="UTF-8">
- <title>垂直滚动条</title>
- <style>
- *{
- padding: 0;
- margin: 0;
- }
- .box{
- width: 300px;
- height: 500px;
- border: 1px solid red;
- padding-right: 20px;
- margin: 100px;
- position: relative;
- }
- .content{
- padding: 5px 18px 10px 5px;
- position: absolute;
- left: 0;
- top: -10px;
- }
- .scroll{
- position: absolute;
- top: 0;
- right: 0;
- background-color: #ccc;
- width: 20px;
- height: 100%;
- }
- .bar{
- width: 100%;
- height: 20px;
- background-color: red;
- border-radius: 10px;
- position: absolute;
- left: 0;
- top: 0;
- cursor: pointer;
- }
- </style>
- </head>
- <body>
- <div class="box" id="box">
- <div class="content">
- 三观不同,一句话都嫌多。我想,人和人之间一定存在磁场这回事,沿着三观向外辐射。
- …………
- </div>
- <div class="scroll">
- <div class="bar"></div>
- </div>
- </div>
- <script>
- var box = document.getElementById('box');
- var content = box.children[0];
- var scroll = box.children[1];
- var bar = scroll.children[0];
- //计算滚动条红色bar的长度:容器长度/内容长度 * 容器长度,,比例关系
- bar.style.height = box.offsetHeight / content.offsetHeight * box.offsetHeight +"px";
- bar.onmousedown = function(event){
- var event = event || window.event;
- var y = event.clientY - this.offsetTop;
- document.onmousemove = function(event){
- var event = event || window.event;
- var top = event.clientY - y;
- if(top < 0)
- top =0;
- else if(top > scroll.offsetHeight - bar.offsetHeight)
- top = scroll.offsetHeight - bar.offsetHeight;
- bar.style.top = top +"px";
- //(内容盒子高度 - 大盒子高度) / (大盒子高度 - 红色盒子的高度) * 红色盒子移动的数值
- content.style.top = -(content.offsetHeight - box.offsetHeight)/(box.offsetHeight - bar.offsetHeight)*top+"px";
- window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); // 防止拖动滑块的时候, 选中文字
- }
- }
- document.onmouseup = function(){
- document.onmousemove = null;
- }
- </script>
- </body>
- </html>
效果:
来源: http://www.phperz.com/article/17/0609/328371.html