<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>验证码</title> <style> .father{ width: 400px; height: 50px; background-color: red; margin: 300px auto; position: relative; } .son{ position: absolute; top: 0; left: 0; height: 100%; width: 40px; background-color: purple; } .mask{ width: 0; height: 100%; background-color: #336699; /*position: absolute; top: 0; left: 0;*/ } </style> <script src="../public.js"></script> </head> <body> <div class="father"> <div class="son"></div> <div class="mask"></div> </div> </body> <script> var father=document.querySelector(".father") var son=document.querySelector(".son") var mask=document.querySelector(".mask") addEvent(son,"mousedown",down) function down(eve) { var e1=eve||window.event; var leftVal = e1.clientX - son.offsetLeft; console.log(e1.clientX)//第一次按下去,鼠标相对于可是页面的X,是一直不会变化的。 console.log(son.offsetLeft)//son相对于包含快的距离; addEvent(document,"mousemove",move) function move(eve) { var e2=eve||window.event console.log(e2.clientX) son.style.left=e2.clientX- leftVal +"px" if(e2.clientX- leftVal<0){ son.style.left="0px" } else if(e2.clientX- leftVal>360){ son.style.left="360px" } mask.style.width = son.style.left; window.getSelection ? window.getSelection().removeAllRanges():document.selection.empty();//清除拖动,防止有时候鼠标弹起来还在拖动。 } addEvent(document,"mouseup",up) function up(eve) { var e3=eve||window.event; removeEvent(document,"mousemove",move) } } </script> </html>