本文详细解析如何使用原生JavaScript实现一个滑动开关按钮。通过SVG的circle元素结合setAttribute控制位置,利用mousedown、mousemove和mouseup事件处理拖拽逻辑。文章重点介绍了使用Promise.then()确保动画结束后清除定时器,以及通过setInterval实现平滑移动的完整代码与核心思路。
原生JS滑动按钮实现概述
以下是利用JavaScript编写的滑动按钮的具体实现代码,供读者参考。
首先展示最终的效果演示图。

接着提供完整的源代码。
完整源代码展示
<!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>
核心知识点与实现步骤解析
接下来详细阐述该功能涉及的核心知识点、制作思路及具体实现步骤。
1、基础布局设置:父容器采用相对定位(position: relative),子元素采用绝对定位(position: absolute)。通过设置 left: 50% 和 top: 50%,并结合 transform: translateX(-50%) 和 translateY(-50%) 实现元素的水平垂直居中。
2、SVG图形控制:利用SVG中的circle元素,通过setAttribute方法动态修改其cx属性来控制圆形的位置移动。
3、异步流程控制:使用Promise对象的then()方法,确保在动画或操作结束后执行clearInterval,以清理定时器。
4、鼠标事件监听:circle元素绑定了mousedown、mousemove和mouseup事件。当触发mousedown事件时,将变量clicked设置为true,从而允许move事件执行重置逻辑。
5、状态重置:当触发mouseup或mouseleave事件时,将clicked变量设置为false,此时move事件中的重置逻辑(停止移动)将无法被触发。
6、复位动画逻辑:在停止状态下,判断圆心当前位于左侧还是右侧。若在左半部分,则利用setInterval启动动画,每10毫秒执行一次,每次移动1.5像素。当检测到圆心到达起始点或终点时,停止动画。
7、样式切换:完成上述逻辑后,进行相应的样式切换以完成交互反馈。
上述代码均为本人原创,欢迎借鉴参考。代码尚未进行深度整理,可能包含无效变量,此处主要展示实现思路。
以上就是本文的全部内容,希望能为读者提供学习帮助,也欢迎大家继续支持本站。