简体   繁体   English

Javascript可移动div-在div移动时防止mousedown与页面上其余文本的交互

[英]Javascript movable div - keep mousedown from interacting with rest of text on page while div moving

I am trying to make a moveable div. 我正在尝试制作一个可移动的div。 I know it is a one liner with jQuery, but I don't want to add the 100k+ for this one feature. 我知道这是jQuery的一个衬板,但我不想为此功能添加100k +。 What I have below works except that when the div moves the rest of the text on the page acts as though the mouse is down and dragging over it (which of course it is) and so the text becomes highlighted or un-highlighted as the mouse moves. 我下面的内容起作用,除了当div移动页面上的其余文本时,就像鼠标按下并在其上拖动(当然是鼠标拖动)一样,因此文本随着鼠标变为突出显示或未突出显示动作。 Are there any relatively "easy" pure javascript solutions to this? 有没有相对“简单”的纯javascript解决方案?

BTW: thanks to jnoreiga for this code. 顺便说一句:感谢jnoreiga的代码。

window.onload = addListeners;

function addListeners(){
    document.getElementById('moveme').addEventListener('mousedown', mouseDown, false);
    window.addEventListener('mouseup', mouseUp, false);
}

function mouseUp()
{
    window.removeEventListener('mousemove', divMove, true);
}

function mouseDown(e){
  window.addEventListener('mousemove', divMove, true);
}

function divMove(e){
    var div = document.getElementById('moveme');
  div.style.position = 'absolute';
  div.style.top = e.clientY + 'px';
  div.style.left = e.clientX + 'px';
}

And some test html 和一些测试HTML

    <div id="moveme" style="width:100px; background-color:red">Test<br><br>Some more text</div>

    <div style="position:absolute; top:100px; left:50px;">
    <h1>Curriculum</h1>
    <ul>
      <li><a href="#">Math</a></li>
      <li><a href="#">Geometry</a></li>
      <li><a href="#">Physics</a></li>
    </ul>
    </div>

I was able to find code here which showed me how to make it work. 我在这里可以找到向我展示如何使其工作的代码。 The issue appears to be in setting OnMouseDown to the div that is to be moved. 问题似乎在于将OnMouseDown设置为要移动的div。 If OnMouseDown is set to window, then the highlighting can be overcome (the tutorial shows how). 如果将OnMouseDown设置为window,则可以克服突出显示(本教程显示了方法)。 I had to modify the code shown to search up the tree to find the parent div being clicked on (eg if an element in the div is taking the mousedown instead of the div itself.) 我必须修改显示的代码以搜索树以找到被单击的父div(例如,如果div中的某个元素正在将mousedown而不是div本身占用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM