2015-09-17 4 views
4

У меня есть HTML-элемент, который обычно перетаскивается. В личном файле он работает, на Codepen это не так.Перемещение элемента JavaScript не работает

Я не понимаю, где проблема.

Мой Codepen

Или JS, CSS и HTML ...

var clicEnCours = false; 
 
var position_x = 0; 
 
var position_y = 0; 
 
var origineDiv_x = 0; 
 
var iExplorer = false; 
 
var deplacable = ""; 
 
if (document.all){ 
 
    iExplorer = true; 
 
} 
 
function elempress(pDiv){ 
 
    chaineX = document.getElementById(pDiv).style.left; 
 
    chaineY = document.getElementById(pDiv).style.top; 
 
    origineDiv_x = x - chaineX.substr(0,chaineX.length-2); 
 
    origineDiv_y = y - chaineY.substr(0,chaineY.length-2); 
 
    clicEnCours = true; 
 
    deplacable = pDiv; 
 
    document.getElementById(deplacable).style.cursor = 'pointer'; 
 
    document.getElementById(deplacable).style.zIndex = 100; 
 
} 
 

 
function elemrelache(pDiv){ 
 
    clicEnCours = false; 
 
    document.getElementById(deplacable).style.cursor = 'grab'; 
 
    document.getElementById(deplacable).style.zIndex = 0; 
 
    deplacable = ""; 
 
} 
 

 

 
function deplacementSouris(e){ 
 

 
    x = (iExplorer) ? event.x + document.body.scrollLeft : e.pageX; 
 
    y = (iExplorer) ? event.y + document.body.scrollTop : e.pageY; 
 
    
 
    if (clicEnCours && document.getElementById){ 
 
    position_x = x - origineDiv_x; 
 
    position_y = y - origineDiv_y; 
 
    document.getElementById(deplacable).style.left = position_x; 
 
    document.getElementById(deplacable).style.top = position_y; 
 
    } 
 
} 
 

 
if(!iExplorer){ 
 
    document.captureEvents(Event.MOUSEMOVE); 
 
} 
 
document.onmousemove = deplacementSouris;
@import url(https://fonts.googleapis.com/css?family=Nova+Mono); 
 

 
#divdrag { 
 
    font-family:'Nova Mono'; 
 
    border-radius:10px; 
 
    background:#26A69A; 
 
    padding:10px; 
 
    width:30%; 
 
}
<div id="divdrag" onmousedown="elempress('divdrag');" onmouseup="elemrelache('divdrag');">Drag me</div>

ответ

0

В top и left свойства требуют единиц. Вы присваиваете им только номера.

document.getElementById(deplacable).style.left = position_x + 'px'; 
document.getElementById(deplacable).style.top = position_y + 'px'; 

Эти 2 свойства также применимы только тогда, когда элемент позиционируется relative или absolute.

#divdrag { 
    position:absolute; 
} 

http://codepen.io/anon/pen/garopb

+0

Спасибо вам, это работает! – ShoLee

Смежные вопросы