Moving a JavaScript Element Doesn't Work

I have an HTML element that is usually draggable. In a personal file it works, on Codepen it is not.

I do not understand where the problem is.

My codepen

Or JS, CSS and 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>
Run code
+4
source share
1 answer

For properties topand leftunits are required. You assign them only numbers.

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

These 2 properties apply only if the element is located relativeor absolute.

#divdrag {
    position:absolute;
}

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

0
source

Source: https://habr.com/ru/post/1607908/


All Articles