2017-07-02 52 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

相關問題