本文主要和大家分享实现JS拖动效果的简单方法,利用CSS3的Trnsform的移动属性来实现的,希望能帮助到大家。
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#dom{
width: 50px;
height: 50px;
border: 2px solid red;
}
</style>
</head>
<body>
<p id="dom"></p>
<script>
(function(){
let dom = document.getElementById('dom');
let moveX,moveY
dom.addEventListener('mousedown',function (e) {
moveX=e.target.offsetWidth;
moveY=e.target.offsetHeight
console.log(e);
document.addEventListener('mousemove',move,false)
})
function move(e){
if(moveY&& moveY){
let width =moveX/2,height = width+moveY;
dom.style.transform='translate('+(e.x-width)+'px,'+(e.y-height)+'px)'
}
}
document.addEventListener('mousemove',move,false)
document.addEventListener('mouseup',function (e) {
let width =moveX/2,height = width+moveY;
let i =(e.x-width) +'px',y=(e.y-height)+'px';
if(moveX && moveY){
document.removeEventListener('mousemove',move,false);
dom.style.transform='translate('+i+','+y+')';
moveY='',moveX=''
}
})
})()
</script>
</body>
</html>相关推荐:
以上就是实现JS拖动效果的简单方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号