利用原生Js制作的滑动按钮
生活随笔
收集整理的這篇文章主要介紹了
利用原生Js制作的滑动按钮
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
利用Js制作的滑動按鈕
首先貼上效果圖
再貼上源碼
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title> </head> <body><div style="position: relative;width:100vw;height:100vh"><div id="container"><svg style="width:inherit;height:inherit"><circle id="c" cx="25" cy="25" r="23" style="fill:white; stroke:gray; stroke-width:2;"onmousedown="down(event)"onmouseup="up(event)"onmouseleave="up(event)"/></svg></div></div><!-- <script>setTimeout(function () {let c = document.querySelector('circle');console.log(c.parentNode.parentNode.style)},500)</script> --><style>body{margin:0;background-color:azure;}#container{position:absolute;left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%);width: 200px;height: 50px;background-color: black;border-radius: 50px;}</style><script>let circle = document.getElementById('c'),clicked = false,x = 0,y = 0;circle.addEventListener("mousemove",function(e){x = e.offsetX;if(clicked){circle.setAttribute("cx",x)}})function t(e){circle.setAttribute("cx",e.offsetX);}function down(e){clicked = true;}function up(){if(clicked){let flag;if(x <= 100)new Promise(function(resolve,reject){flag = setInterval(function(){x -= 2;circle.setAttribute("cx",x);if(x <= 25){circle.setAttribute("cx",25)circle.setAttribute("style","fill:white; stroke:gray; stroke-width:2;")resolve("ok")}})}).then(res => {clearInterval(flag)})else new Promise(function(resolve,reject){flag = setInterval(function(){x += 2;circle.setAttribute("cx",x);if(x >= 175){circle.setAttribute("cx",175);circle.setAttribute("style","fill:black; stroke:gray; stroke-width:2;")resolve("ok")}})}).then(res => {clearInterval(flag)})}clicked = false;}</script></body> </html>知識點和制作思路及步驟
基本布局(父相子絕,left: 50%; top: 50%; transform: translateX(-50%)
translateY(-50%);)
svg的circle( cx )控制移動, 對于circle的cx采用setAtrribute來進行控制。
**Promise.then()**用來保證結束后進行clearInterval
circle監聽了mousemove,mouseup,mousedown事件。 當mousedown事件觸發會將cliked置為true進而move事件會進行reset;
mouseup和mouseleave會將cliked置為false;進而無法觸發move事件的reset(停止);
當停止狀態下,判斷原點在左側還是右側, 動畫: 如果在左半部分則利用setInterval進行10ms一幀每次1.5px的移動,判斷到達開始或者結束點則停止。
再進行樣式切換。
代碼本人全部原創,請盡情抄襲,
代碼寫完沒有經過整理,可能存在無效變量,僅僅代表我的思路。
總結
以上是生活随笔為你收集整理的利用原生Js制作的滑动按钮的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 锂电池行业锂溶液除杂的原理分析
- 下一篇: 蓝牙模块(HC-05)与手机连接,蓝牙与