今天要分享的是运用原生JS拖拽进度条改变元素透明度,效果如下:
以下是代码实现,欢迎大家复制粘贴。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>原生JS拖拽进度条改变元素透明度</title> <style> #parent { width: 400px; height: 20px; background: #CCC; position: relative; margin: 20px auto; } #div1 { width: 20px; height: 20px; background: red; cursor: pointer; position: absolute; } #div2 { width: 300px; height: 300px; margin: 0 auto; filter: alpha(opacity:0); opacity: 0; background: yellow; } </style> <script> window.onload = function () { var oDiv = document.getElementById('div1'); var oParent = document.getElementById('parent'); var oDiv2 = document.getElementById('div2'); oDiv.onmousedown = function (ev) { var oEvent = ev || event; //计算鼠标相对滑块上的位置 var disX = oEvent.clientX - oDiv.offsetLeft; document.onmousemove = function (ev) { var oEvent = ev || event; //计算滑块的动态left值 var l = oEvent.clientX - disX; //限制拖拽范围 if (l < 0) { l = 0; } else if (l > oParent.offsetWidth - oDiv.offsetWidth) { l = oParent.offsetWidth - oDiv.offsetWidth; } oDiv.style.left = l + 'px'; //计算拖拽移动距离与可拖动总范围的比例 var scale = l / (oParent.offsetWidth - oDiv.offsetWidth); //让Div2跟随鼠标的拖动逐渐显示与隐藏 oDiv2.style.filter = 'alpha(opacity:' + 100 * scale + ')'; oDiv2.style.opacity = scale; }; document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; }; }; }; </script> </head> <body> <div id="parent"> <div id="div1"></div> </div> <div id="div2"></div> </body> </html>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
长按识别二维码并关注微信
更方便到期提醒、手机管理