javascript拖拽滑动条
本文将会介绍两种拖拽滑动条的情况,有需要的小伙伴可以参考一下。
1、被拖拽内容长度小于父元素内容长度,效果图如下所示:
代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> #div0 { width: 500px; height: 30px; position: absolute; border: 1px solid gray; } #div1 { position: absolute; width: 100px; height: 30px; background: red; cursor: move; } </style> </head> <body> <div id="div0"> <div id="div1"></div> </div> </body> </html> <script> div1.onmousedown = function (e) { var _x = e.clientX - div1.offsetLeft; document.onmousemove = function (e) { var x = e.clientX - _x; if (x < 0) { x = 0 } if (x > div0.offsetWidth - div1.offsetWidth - 2) { x = div0.offsetWidth - div1.offsetWidth - 2 } div1.style.left = x + "px"; } document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; } return false; } </script>
2、被拖拽内容长度大于父元素内容长度,效果图如下所示:
代码:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> * { margin: 0; padding: 0; } html, body { width: 100%; height: 100%; overflow: hidden; } .div0 { width: 390px; height: 40px; position: relative; margin: 100px auto; overflow: hidden; } .div1 { position: absolute; white-space: nowrap; font-size: 0px; } ul li { list-style: none; display: inline-block; width: 129px; height: 40px; border-right: 1px solid black; background: blue; font-size: 14px; } </style> </head> <body> <div class="div0" id="div0"> <div class="div1" id="div1"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> </ul> </div> </div> <script> div1.onmousedown = function (e) { var _x = e.clientX - div1.offsetLeft; document.onmousemove = function (e) { var x = e.clientX - _x; if (x > 0) { x = 0 } if (x < div0.offsetWidth - div1.offsetWidth) { x = div0.offsetWidth - div1.offsetWidth } div1.style.left = x + "px"; } document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; } return false; } </script> </body> </html>