我只是想改变div位置onclick,当我点击身体时我希望div出现在那里。
#elem{
width: 100px;
height: 100px;
border: 1px solid red;
position: absolute;
top: 0;
left: 150px;
}
var elem = document.getElementById("elem");
elem.onclick = funct;
function funct( event ){
var x = event.clientX;
var y = event.clientY;
this.style.top = y + 'px';
this.style.left = x + 'px';
}
答案 0 :(得分:0)
以下是工作示例。您需要向document / body元素添加事件侦听器:
var target = document.getElementById('target');
document.addEventListener('click', function (e) {
target.style.left = e.clientX + 'px';
target.style.top = e.clientY + 'px';
});

#target {
width: 50px;
height: 50px;
background-color: #ccc;
position: absolute;
}

<div id="target"></div>
&#13;
您可以进一步展开处理程序并将div置于光标位置的中心位置:
var target = document.getElementById('target');
document.addEventListener('click', function (e) {
target.style.left = e.clientX - target.offsetWidth / 2 + 'px';
target.style.top = e.clientY - target.offsetHeight / 2 + 'px';
});
&#13;
#target {
width: 50px;
height: 50px;
background-color: #ccc;
position: absolute;
}
&#13;
<div id="target"></div>
&#13;