我是JS初学者。
我做了一个可拖动的<div>
。当我拖动它时,它将在<div>
附近选择一个或两个单词或使用蓝色选择框选择闪烁(请参阅下面的代码片段)。
这让经历感到困扰。我最想要的是在拖动<div>
时保持选择其他正常单词。
请帮我优化代码或告诉我是否存在语法错误。
window.onload = function() {
var parent = document.getElementById('parent');
eventFunc.addEventListener(parent, 'mousedown', dragItem);
}
function dragItem(ev) {
ev = ev || window.event;
var element = eventFunc.target(ev);
var spaceX = ev.clientX - element.offsetLeft,
spaceY = ev.clientY - element.offsetTop,
maxX = (document.documentElement.clientWidth || document.body.clientWidth) - element.offsetWidth,
maxY = (document.documentElement.clientHeight || document.body.clientHeight) - element.offsetHeight;
document.onmousemove = function(ev) {
ev = ev || window.event;
eventFunc.stopPropagation(ev);
element.style.left = (ev.clientX - spaceX) + 'px';
element.style.top = (ev.clientY - spaceY) + 'px';
if (element.offsetLeft < 0) {
element.style.left = 0;
} else if (element.offsetLeft > maxX) {
element.style.left = maxX + 'px'
}
if (element.offsetTop < 0) {
element.style.top = 0;
} else if (element.offsetTop > maxY) {
element.style.top = maxY + 'px'
}
}
document.onmouseup = function() {
document.onmousemove = null;
document.onmouseup = null;
}
}
var eventFunc = {
addEventListener: function(element, type, func) {
if (addEventListener) {
element.addEventListener(type, func, false);
} else if (attachEvent) {
element.attachEvent('on' + type, func);
} else {
element['on' + type] = func;
}
},
target: function(ev) {
return ev.target || ev.srcElement;
},
stopPropagation: function(ev) {
if (ev.stopPropagation) {
ev.stopPropagation();
} else {
ev.cancelBubble = true;
}
},
preventDefault: function(ev) {
if (ev.preventDefault) {
ev.preventDefault();
} else {
ev.returnValue = false;
}
}
}
&#13;
#parent {
width: 400px;
height: 300px;
position: absolute;
border: 3px solid #ccc;
top: 0;
left: 0;
cursor: all-scroll;
text-align: center;
font: bold 35px/35px'Segoe UI', arial, helvetica, sans-serif;
color: #ccc;
}
#children {
text-align: left;
color: initial;
font: initial;
cursor: auto;
margin: 1em;
border: 1px solid red;
}
&#13;
Outside Words
<div id="parent">
<div id="children">I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element. I'm The Children Element.</div>
DRAG ME
</div>
</body>
&#13;
答案 0 :(得分:0)
在dragItem
函数内....添加以下行...
function dragItem(ev) {
ev.preventDefault()
}
[编辑(完成剩下的问题)]
要选择任何内容的内容......您可以使用此功能......
function selectNode(el) {
var range = document.createRange()
range.selectNodeContents(el)
var sel = window.getSelection()
sel.removeAllRanges()
sel.addRange(range)
}
//通过传递节点
来使用它selectNode(document.getElementById('parent'))