我目前正在javascript中制作一个“拖放”引擎。当我拿起一个元素来移动它时,光标从cursor: move
(我在css中设置)变为cursor: text
,这是我不想要的。它还可以选择(突出显示)来自其他元素的文本,同时我移动拖动对象(我再也不想)。如何防止这些问题发生?
// JavaScript Document
var posX;
var posY;
var element;
var currentPos;
document.addEventListener("mousedown", drag, false);
function drag(event) {
if(event.target.className == "square") {
element = event.target;
currentPos = findPos(element);
posX = event.clientX -currentPos.x; //-parseInt(element.offsetLeft);
posY = event.clientY -currentPos.y; //-parseInt(element.offsetTop);
document.addEventListener("mousemove", move, false);
}
}
function move(event) {
if (typeof(element.mouseup) == "undefined")
document.addEventListener("mouseup", drop, false);
//Prevents redundantly adding the same event handler repeatedly
element.style.left = event.clientX - posX + "px";
element.style.top = event.clientY - posY + "px";
}
function drop() {
document.removeEventListener("mousemove", move, false);
document.removeEventListener("mouseup", drop, false);
//alert("DEBUG_DROP");
}
function findPos(obj) { // Donated by `lwburk` on StackOverflow
var curleft = curtop = 0;
if (obj.offsetParent) {
do {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return { x: curleft, y: curtop };
}
}
CSS:
.square {
position: absolute;
width: 100px;
height: 100px;
background: red;
cursor:move;
}
p {
padding: 0px;
margin: 0px;
outline-style: dotted;
outline-color: #000;
outline-width: 1px;
}
HTML:
<body>
<p class="square">Thing One</p>
<p class="square">Thing Two</p>
</body>
非常感谢你阅读,甚至更多的帮助!这意味着很多,特别是因为我刚开始学习这门语言。
答案 0 :(得分:0)
嘿 为了防止突出显示你可以使用CSS:
* {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
在事件处理程序put
中防止默认操作(可能是光标更改的原因?)event.preventDefault()
其中event是您的事件(传递给处理程序)。您还可以尝试在事件处理程序中设置CSS属性:
event.target.setAttribute("style","cursor: move;");
答案 1 :(得分:0)
<p class="square" ondragstart="return false" onselectstart="return false">Thing One</p>