这一段代码直接放到网页上运行,div是无法拖动的,但是如果把#div的样式,内联在div标签中,就可以拖动了,这是为什么?(<div class="a" id="div" style="left:500px;top:100px;"></div>)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js实现拖动div块</title>
<style>
#div{
width: 500px;
height: 300px;
border: 2px solid #ccc;
position: absolute;
}
</style>
</head>
<body>
<div class="a" id="div"></div>
<script type="text/javascript">
var px,py;
var div = document.getElementById('div');
div.onmousedown = function(e) {
var e = e || window.event;
px = e.clientX - parseInt(div.style.left);
py = e.clientY - parseInt(div.style.top);
div.onmousemove = mousemove;
}
div.onmouseup = function(){
div.onmousemove = null;
}
function mousemove(e){
var e = e || window.event;
div.style.left = (e.clientX-px)+'px';
div.style.top = (e.clientY-py)+'px';
}
</script>
</body>
</html>
js只能改变行内样式。你的获取方式不对