2017-07-02 59 views
0

我无法正确拖动“父”框到页面上的另一个点。 如果我不放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"> 
 
\t \t \t <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"> 
 
\t \t \t <span id="second-child" style="color:red;">Text</span> 
 
    </span> 
 
    </p> 
 
</body>

回答

0

你可以试试这个。这工作得很好...检查是否是对你有帮助..

\t \t var makeMove; 
 
\t \t x0=0; 
 
\t \t y0=0; 
 
\t \t function move(e){ 
 
\t \t \t if(makeMove){ 
 
\t \t \t \t x1 = e.clientX; 
 
\t \t \t \t y1 = e.clientY; 
 
\t \t \t \t cx=x0+x1-x; 
 
\t \t \t \t cy=y0+y1-y; 
 
\t \t \t \t 
 
\t \t \t \t document.getElementById("main").style.left = cx +"px"; 
 
\t \t \t \t document.getElementById("main").style.top = cy +"px"; 
 
\t \t \t \t e.preventDefault(); 
 
\t \t \t } 
 
\t \t } 
 
\t \t function mouseUp(e){ 
 
\t \t \t makeMove=false; 
 
\t \t \t x0=cx; 
 
\t \t \t y0=cy; 
 
\t \t } 
 
\t \t function mouseDown(e){ 
 
\t \t \t makeMove=true; 
 
\t \t \t x = e.clientX; 
 
\t \t \t y = e.clientY; 
 
\t \t }
<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>

+0

该解决方案不能在我的情况下工作:按照文本移动容器,它必须是部分文字。 – User

相关问题