ホームページ  >  記事  >  ウェブフロントエンド  >  js はドラッグ アンド ドロップと吸着コード共有を実装します

js はドラッグ アンド ドロップと吸着コード共有を実装します

小云云
小云云オリジナル
2018-03-02 13:57:571802ブラウズ

この記事では主に 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。