這篇文章將為大家詳細(xì)講解有關(guān)利用JavaScript如何在移動端實(shí)現(xiàn)一個(gè)拖動元素,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

代碼實(shí)現(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; // 獲取手指初始坐標(biāo)
var startY = 0;
var x = 0; // 獲得盒子原來的位置
var y = 0;
// 手指觸摸
div.addEventListener('touchstart', function(e) {
// 獲取手指初始坐標(biāo)
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) {
// 計(jì)算手指的移動距離:手指移動之后的坐標(biāo)減去手指初始的坐標(biāo)
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(); // 阻止屏幕滾動的默認(rèn)行為
});
</script>
</body>
</html>
新聞名稱:利用JavaScript如何在移動端實(shí)現(xiàn)一個(gè)拖動元素-創(chuàng)新互聯(lián)
鏈接分享:http://chinadenli.net/article8/gejop.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站、定制網(wǎng)站、移動網(wǎng)站建設(shè)、網(wǎng)站營銷、外貿(mào)建站、關(guān)鍵詞優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容