JavaScript實現(xiàn)移動端拖動元素
更新時間:2020年11月24日 15:45:26 作者:火星飛鳥
這篇文章主要為大家詳細介紹了JavaScript實現(xiàn)移動端拖動元素,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了JavaScript實現(xiàn)移動端拖動元素的具體代碼,供大家參考,具體內容如下
實現(xiàn)效果:

請切換到移動端頁面查看!

代碼實現(xiàn):
<!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>
body {
background-color: #1cee89;
}
div {
position: absolute;
left: 0;
width: 100px;
height: 100px;
background-color: #8294ff;
border-radius: 20px;
}
</style>
</head>
<body>
<div></div>
<script>
var div = document.querySelector('div');
var startX = 0; // 獲取手指初始坐標
var startY = 0;
var x = 0; // 獲得盒子原來的位置
var y = 0;
// 手指觸摸
div.addEventListener('touchstart', function(e) {
// 獲取手指初始坐標
startX = e.targetTouches[0].pageX;
startY = e.targetTouches[0].pageY;
x = this.offsetLeft;
y = this.offsetTop;
this.style.boxShadow = '0 0 15px rgba(0, 0, 0, .6)';
});
// 手指離開
div.addEventListener('touchend', function(e) {
this.style.boxShadow = '';
});
// 手指按住移動
div.addEventListener('touchmove', function(e) {
// 計算手指的移動距離:手指移動之后的坐標減去手指初始的坐標
var moveX = e.targetTouches[0].pageX - startX;
var moveY = e.targetTouches[0].pageY - startY;
// 移動盒子 盒子原來的位置 + 手指移動的距離
this.style.left = x + moveX + 'px';
this.style.top = y + moveY + 'px';
e.preventDefault(); // 阻止屏幕滾動的默認行為
});
</script>
</body>
</html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
next.js初始化參數設置getServerSideProps應用學習
這篇文章主要為大家介紹了next.js初始化參數設置getServerSideProps的應用示例學習,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10

