移动一个容器和所有孩子

时间:2017-07-02 15:53:11

标签: javascript jquery html parent-child contenteditable

我无法正确地将“父亲”框拖到页面上的另一个点。 如果我没有打开e.preventDefault,浏览器会通过移动元素而忽略范围上的方向而不重新创建另一个容器。 我需要能够正确移动容器。父亲,我该怎么办? 实时代码为here

var span;
var clone;
var id;
window.onload = function() {
  id = document.getElementsByClassName('father')[0];
  var b = document.body;
  id.addEventListener("dragstart", dragStart, false);
  id.addEventListener("dragend", dragEnd, false);
  b.addEventListener('drop', function(event) {
    dropp(event)
  }, false);
}

function dragStart() {
  span = document.getElementsByClassName('father')[0];
  clone = span.cloneNode(true);
}

function dragEnd() {
  if (document.getSelection) {
    range = window.getSelection().getRangeAt(0);
    range.insertNode(clone);
  }
}

function dropp(e) {
  e.preventDefault();
}
<body contenteditable="true">
  <p> first paragraph </p>
  <p> second paragraph
    <span class="father">
			<img id="first-child" src="http://www.telegraph.co.uk/content/dam/Travel/Destinations/Africa/Mauritius/Mauritius---Beaches---Tropical-beach-large.jpg" width="200" height="auto">
			<span id="second-child" style="color:red;">Text</span>
    </span>
  </p>
</body>

1 个答案:

答案 0 :(得分:0)

你可以试试这个。这很好用......检查它是否对你有帮助..

		var makeMove;
		x0=0;
		y0=0;
		function move(e){
			if(makeMove){
				x1 = e.clientX;
				y1 = e.clientY;
				cx=x0+x1-x;
				cy=y0+y1-y;
				
				document.getElementById("main").style.left = cx +"px";
				document.getElementById("main").style.top = cy +"px";
				e.preventDefault();
			}
		}
		function mouseUp(e){
			makeMove=false;
			x0=cx;
			y0=cy;
		}
		function mouseDown(e){
			makeMove=true;
			x = e.clientX;
			y = e.clientY;
		}
<body contenteditable="true">
    <p> first paragraph </p>
    <p  onmousemove="move(event)" onmouseup="mouseUp(event)" onmousedown="mouseDown(event)"> second paragraph
      <span class="father" id="main" style="position:relative;">
        <img id="first-child" src="http://www.telegraph.co.uk/content/dam/Travel/Destinations/Africa/Mauritius/Mauritius---Beaches---Tropical-beach-large.jpg" width="200" height="auto">
        <span id="second-child" style="color:red;">Text</span>
      </span>
    </p>
</body>