<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>拖动条</title> <style> *{ padding: 0; margin: 0; } .box1{ 600px; height: 10px; background-color: red; margin: 300px auto; position: relative; } .box2{ height: 30px; 40px; background-color: pink; position: absolute; left: 0; top: -10px; } .box1 span{ 40px; height: 40px; position: absolute; background-color: yellow; left: -50px; top: -15px; text-align: center; line-height: 40px; } .box1 p{ 40px; height: 40px; position: absolute; top: -15px; left: 600px; text-align: center; line-height: 40px; } </style> <script src="../public.js"></script> </head> <body> <div class="box1"> <span id="txt"></span> <p>10</p> <div class="box2"></div> </div> </body> <script> var otxt=document.querySelector("#txt"); var oBox1=document.querySelector(".box1"); var oBox2=document.querySelector(".box2"); addEvent(oBox2,"mousedown",hit) function hit(eve) { var e1=eve||window.event; addEvent(document,"mousemove",move) function move(eve) { var e2=eve||window.event; var x=e2.clientX-oBox1.offsetLeft-e1.offsetX; if(x<=0){ x=0; } else if(x>=560){ x=560 } oBox2.style.left=x+"px" // 清除拖动 --- 防止鼠标已经弹起时还在拖动 var a=(x/560*10).toFixed(1) otxt.innerHTML=a window.getSelection ? window.getSelection().removeAllRanges():document.selection.empty(); } addEvent(document,"mouseup",up) function up() { removeEvent(document,"mousemove",move) } stopDefault(e1)//按下的时候清除默认,防止选中了文字无法拖动 } </script> </html>