您好,登錄后才能下訂單哦!
小編給大家分享一下JavaScript實(shí)現(xiàn)垂直滾動(dòng)條效果的方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
具體內(nèi)容如下
1、紅色盒子高度計(jì)算公式:
容器的高度 / 內(nèi)容的高度 * 容器的高度
2、紅色方塊移動(dòng)一像素 ,我們的內(nèi)容盒子移動(dòng)多少呢?
(內(nèi)容盒子高度 - 大盒子高度) / (大盒子高度 - 紅色盒子的高度) 計(jì)算倍數(shù)
(內(nèi)容盒子高度 - 大盒子高度)/ (大盒子高度 - 紅色盒子的高度) * 紅色盒子移動(dòng)的數(shù)值
<html> <head> <meta charset="UTF-8"> <title>垂直滾動(dòng)條</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"> 三觀不同,一句話都嫌多。我想,人和人之間一定存在磁場(chǎng)這回事,沿著三觀向外輻射。 ………… </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]; //計(jì)算滾動(dòng)條紅色bar的長(zhǎng)度:容器長(zhǎng)度/內(nèi)容長(zhǎng)度 * 容器長(zhǎng)度,,比例關(guān)系 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"; //(內(nèi)容盒子高度 - 大盒子高度) / (大盒子高度 - 紅色盒子的高度) * 紅色盒子移動(dòng)的數(shù)值 content.style.top = -(content.offsetHeight - box.offsetHeight)/(box.offsetHeight - bar.offsetHeight)*top+"px"; window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); // 防止拖動(dòng)滑塊的時(shí)候, 選中文字 } } document.onmouseup = function(){ document.onmousemove = null; } </script> </body> </html>
效果:
以上是“JavaScript實(shí)現(xiàn)垂直滾動(dòng)條效果的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。