zl程序教程

您现在的位置是:首页 >  前端

当前栏目

javascript: 自定义鼠标拖动的滑块slider(chrome 105.0.5195.125)

JavaScriptChrome 自定义 鼠标 拖动 滑块 slider
2023-09-14 08:59:32 时间

一,js代码

<html>
<head>
    <meta charset="utf-8"/>
    <title>测试</title>
</head>
<body onmousemove="divmousemoving()" onMouseUp="divmouseup()">

<div style="margin: auto;position: absolute;top: 100px;left: 50%;transform: translateX( -50% );">
<div style="width:700px;height:50px;background: #ffff00;position: relative;" >
  <!--可以拖动的按钮 begin-->
  <div id="btn" style="width:50px;height:50px;border-radius: 25px;background: #ff0000;position: absolute;left:-25px;" 
onmousedown
="divmousedown()"></div> <!--可以拖动的按钮 end--> </div> </div> <script> //拖动开始时的位置x,y var x = 0; var y = 0; //拖动开始时的偏移量 var l = 0; var t = 0; //当前鼠标是否按下 var isDown = false; //开始拖动 function divmousedown(){ if (isDown == true) { return false; } var e = window.event || arguments.callee.caller.arguments[0]; //获取x坐标和y坐标 x = e.clientX; y = e.clientY; //获取左部和顶部的偏移量 l = document.getElementById('btn').offsetLeft; t = document.getElementById('btn').offsetTop; //设置鼠标状态为按下 isDown = true; } //移动 function divmousemoving(){ if (isDown == false) { return; } var e = window.event || arguments.callee.caller.arguments[0]; //得到当前滑动到的位置 var nx = e.clientX; var ny = e.clientY; //计算移动后的左偏移量和顶部的偏移量 var nl = nx - (x - l); var nt = ny - (y - t); //按钮不超出范围 if (nl < -25) { nl = -25; } if (nl > 675) { nl = 675; } console.log("nl:"+nl); document.getElementById('btn').style.left = nl + 'px'; //document.getElementById('btn').style.top = nt + 'px'; } //鼠标松开 function divmouseup(){ console.log("------------------停下来了"); isDown = false; let position = parseInt(document.getElementById('btn').style.left); console.log("position:"+position); } </script> </body> </html>

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: 371125307@qq.com

二,测试效果

三,查看chrome的版本: