我想移动我的"机器人";Div,所以我写了一个javascript代码:
document.addEventListener('mousedown', function(event) {
let robot = document.querySelector('.robot');
robot.clientTop = event.pageX + 'px';
robot.clientLeft = event.pageY + 'px';
});
.robot {
background-color: rgb(10, 0, 143);
height: 120px;
width: 120px;
border-radius: 15px;
margin: 25px auto;
}
<div class="robot">
<span class="eyes_left">
</span>
<span class="eyes_right">
</span>
<div class="hands">
</div>
<div class="battery">
<div class="charge">
</div>
<div class="charge">
</div>
<div class="charge">
</div>
<div class="charge">
</div>
</div>
</div>
但是它不工作,不要说任何错误,问题是什么??
遗憾的是,您无法按照您所尝试的方式设置clientTop。你需要使用css来调整位置。给元素的位置:absolute,然后在javascript中更新顶部和左侧的位置。
document.addEventListener('mousedown', function(event) {
let robot = document.querySelector('.robot');
robot.style.top = event.pageY + 'px';
robot.style.left = event.pageX + 'px';
});
.robot {
background-color: rgb(10, 0, 143);
height: 120px;
width: 120px;
border-radius: 15px;
margin: 25px auto;
position: absolute;
}
<div class="robot">
<span class="eyes_left">
</span>
<span class="eyes_right">
</span>
<div class="hands">
</div>
<div class="battery">
<div class="charge">
</div>
<div class="charge">
</div>
<div class="charge">
</div>
<div class="charge">
</div>
</div>
</div>
使用此方法
let robot = document.querySelector('.robot');
document.addEventListener('mousedown' , function (event){
let y = event.pageY + 'px';
let x = event.pageX + 'px';
robot.setAttribute('style', `top: ${y}; left: ${x}`);
console.log(`Position Updated, top: ${y}; left: ${x}`)
});
.robot{
background-color: rgb(10, 0, 143);
height:120px;
width:120px;
border-radius:15px;
position: relative;
}
<div class="robot">
<span class="eyes_left">
</span>
<span class="eyes_right">
</span>
<div class="hands">
</div>
<div class="battery">
<div class="charge">
</div>
<div class="charge">
</div>
<div class="charge">
</div>
<div class="charge">
</div>
</div>
</div>
https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTophttps://developer.mozilla.org/en-US/docs/Web/API/Element/clientLeft
clientTop
和clientLeft
是只读属性