我正在学习如何在javascript中拖放文档周围的DIV。这是一个现场演示:
这在Firefox中运行良好,我目前没有使用任何其他浏览器进行开发。但是,如果您将set_coords_in_js
更改为false
,则演示会失败。
使用Firebug设置一些断点,您会注意到此行失败:
var div_left = parseInt( mov_div_1.style.left, 10 );
此时mov_div_1.style.left
没有任何价值。因此,javascript不知道现有值是什么,并将div_left
设置为“NaN”。此样式是设置,并且在文档中显示有效,但DOM中没有值!
如果您将set_coords_in_js
设置回true
,则上面有一个值,一切都运行正常。
为什么?
如果您想在本地播放,请将其复制并粘贴到您的本地演示文件中。要查看Firebug中的值(或缺少值),请在 39 或 40 行设置断点,然后单步执行,将鼠标悬停在行中的内容上。请务必将set_coords_in_js
设置为false
以查看问题。
drag_move_div.html
:
<!DOCTYPE html>
<html>
<head>
<title>drag move div demo</title>
<style type='text/css'>
.movDiv {
position: absolute;
left: 80px;
top: 80px;
cursor: move;
border: 1px dashed green;
padding: 1em;
}
.coordinates_display { font-weight: bold; }
</style>
<script type='text/javascript'>
window.onload = function() {
mov_div_1 = document.getElementById('mov_div_1');
set_coords_in_js = true;
function update_coordinates( newX, newY ) {
document.getElementById('coordinate_x').innerHTML = newX;
document.getElementById('coordinate_y').innerHTML = newY;
}
// why do I need to set these here in javascript when they are set in css?
if( set_coords_in_js ) {
mov_div_1.style.left = '80px';
mov_div_1.style.top = '80px';
}
update_coordinates( mov_div_1.style.left, mov_div_1.style.top );
mov_div_1.onmousedown = function(e){
mov_div_1.style.backgroundColor = 'black';
mov_div_1.style.color = 'white';
var div_left = parseInt( mov_div_1.style.left, 10 );
var div_top = parseInt( mov_div_1.style.top, 10 );
var startX = e.clientX;
var startY = e.clientY;
mov_div_1.onmousemove = function(e){
var newX = ( div_left + e.clientX - startX );
var newY = ( div_top + e.clientY - startY );
mov_div_1.style.left = newX + 'px';
mov_div_1.style.top = newY + 'px';
update_coordinates( mov_div_1.style.left, mov_div_1.style.top );
};
};
mov_div_1.onmouseup = function(){
mov_div_1.onmousemove = null;
mov_div_1.style.backgroundColor = '';
mov_div_1.style.color = '';
};
};
</script>
</head>
<body>
<div class='movDiv' id='mov_div_1'>[ Click & Drag Me Around (slowly) ]</div>
<p>Coordinates:
<span id='coordinate_x' class='coordinates_display'></span> x
<span id='coordinate_y' class='coordinates_display'></span></p>
</body>
</html>
答案 0 :(得分:4)
见this related question。当您访问element.style
时,您没有访问计算样式(包括样式表声明),您正在访问元素本身的“样式”属性。因此,当您尝试从mov_div_1.style
获取值时,没有样式属性可用,并且它将作为空字符串返回。
要解决此问题,您需要使用element.currentStyle
(我认为是较旧的IE版本)或element.getComputedStyle()
(现代浏览器):
var computedStyle = mov_div_1.currentStyle || getComputedStyle(mov_div_1);
var div_left = parseInt( computedStyle.left, 10 );
var div_top = parseInt( computedStyle.top, 10 );