首頁 > web前端 > js教程 > 主體

js實作拖曳與吸附程式碼分享

小云云
發布: 2018-03-02 13:57:57
原創
1802 人瀏覽過

本文主要跟大家分享js實作拖曳和吸附程式碼,希望能幫助大家。

<!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>
* {
padding: 0;
margin: 0;
}
#big {
width: 500px;
height: 500px;
background-color: #ccc;
position: relative
}
#box {
width: 100px;
height: 100px;
background-color: #f00;
position: absolute
}
</style>
<script>
window.onload = function () {
var box = document.getElementById(&#39;box&#39;);
var big = document.getElementById(&#39;big&#39;);
// 鼠标在box中的位置
var disX = 0,
disY = 0;
box.onmousedown = function (e) {
var thisE = e || event;
disX = thisE.clientX - box.offsetLeft;
disY = thisE.clientY - box.offsetTop;
document.onmousemove = function (ev) {
var thisEvent = ev || event;
var l = thisEvent.clientX - disX;
var t = thisEvent.clientY - disY;
if (l < 20) {
l = 0;
} else if (l > big.offsetWidth - box.offsetWidth - 20) {
l = big.offsetWidth - box.offsetWidth;
}
if (t < 20) {
t = 0;
} else if (t > big.offsetHeight - box.offsetHeight - 20) {
t = big.offsetHeight - box.offsetHeight;
}
box.style.left = l + &#39;px&#39;;
box.style.top = t + &#39;px&#39;;
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
e.preventDefault();
}
}
</script>
</head>
<body>
<p id="big">
<p id="box"></p>
</p>
</body>
</html>
登入後複製

相關推薦:

js程式碼實作滑​​鼠拖曳div實例

js控制檔拖曳及取得拖曳內容

限制範圍拖曳,磁性吸附。

以上是js實作拖曳與吸附程式碼分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!