js实现兼容PC端和移动端滑块拖动选择数字效果
本文为大家分享了js实现移动端滑块拖动选择数字的效果,可以通过鼠标拖拽滑动效果来选择数字,供大家参考,具体内容如下
<!DOCTYPEhtml> <htmllang="zh-cn"> <head> <metahttp-equiv="Content-Type"content="text/html;charset=gb2312"> <metaname="viewport"content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/> <title>鼠标拖动小方块</title> <styletype="text/css"> .lineDiv{ position:relative; height:5px; background:red; width:300px; margin:50pxauto; } .lineDiv.minDiv{ position:absolute; top:-5px; left:0; width:15px; height:15px; background:green; cursor:pointer } .lineDiv.minDiv.vals{ position:absolute; font-size:20px; top:-45px; left:-10px; width:35px; height:35px; line-height:35px; text-align:center; background:blue; } .lineDiv.minDiv.vals:after{ content:""; width:0px; height:0px; border-top:6pxsolidblue; border-left:6pxsolidtransparent; border-right:6pxsolidtransparent; border-bottom:6pxsolidtransparent; display:block; margin-left:11px; } </style> </head> <body> <center> <h3>用鼠标拖动小方块<spanid="msg">0</span>%</h3> </center> <divid="lineDiv"class="lineDiv"> <divid="minDiv"class="minDiv"> <divid="vals"class="vals">0</div> </div> </div> <script> window.onload=function(){ varlineDiv=document.getElementById('lineDiv');//长线条 varminDiv=document.getElementById('minDiv');//小方块 varmsg=document.getElementById("msg"); varvals=document.getElementById("vals"); varifBool=false;//判断鼠标是否按下 //事件 varstart=function(e){ e.stopPropagation(); ifBool=true; console.log("鼠标按下") } varmove=function(e){ console.log("鼠标拖动") if(ifBool){ if(!e.touches){//兼容移动端 varx=e.clientX; }else{//兼容PC端 varx=e.touches[0].pageX; } //varx=e.touches[0].pageX||e.clientX;//鼠标横坐标varx varlineDiv_left=getPosition(lineDiv).left;//长线条的横坐标 varminDiv_left=x-lineDiv_left;//小方块相对于父元素(长线条)的left值 if(minDiv_left>=lineDiv.offsetWidth-15){ minDiv_left=lineDiv.offsetWidth-15; } if(minDiv_left<0){ minDiv_left=0; } //设置拖动后小方块的left值 minDiv.style.left=minDiv_left+"px"; msg.innerText=parseInt((minDiv_left/(lineDiv.offsetWidth-15))*100); vals.innerText=parseInt((minDiv_left/(lineDiv.offsetWidth-15))*100); } } varend=function(e){ console.log("鼠标弹起") ifBool=false; } //鼠标按下方块 minDiv.addEventListener("touchstart",start); minDiv.addEventListener("mousedown",start); //拖动 window.addEventListener("touchmove",move); window.addEventListener("mousemove",move); //鼠标松开 window.addEventListener("touchend",end); window.addEventListener("mouseup",end); //获取元素的绝对位置 functiongetPosition(node){ varleft=node.offsetLeft;//获取元素相对于其父元素的left值varleft vartop=node.offsetTop; current=node.offsetParent;//取得元素的offsetParent //一直循环直到根元素 while(current!=null){ left+=current.offsetLeft; top+=current.offsetTop; current=current.offsetParent; } return{ "left":left, "top":top }; } } </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。