我有一个HTML元素,通常是可拖动的。在个人文件上,它可以在Codepen上运行,但它没有。
我不明白问题所在。
我的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 :(得分:0)
top
和left
属性需要单位。您只是为他们分配数字。
document.getElementById(deplacable).style.left = position_x + 'px';
document.getElementById(deplacable).style.top = position_y + 'px';
这两个属性也仅适用于元素位于relative
或absolute
的位置。
#divdrag {
position:absolute;
}