You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击鼠标移动div时style.left失效,style.backgroundColor正常,求助

问题解决:style.left 属性不生效的原因及修复方案

问题根源

块级元素(如<div>)默认定位方式为static,left、top这类位置偏移属性仅对非static定位的元素生效(包括relative、absolute、fixed)。你的代码未给.box设置定位,因此style.left无法生效,但backgroundColor属于基础样式属性,不受定位规则限制,所以能正常工作。

修复方案

只需给.box添加非static定位即可,推荐在CSS中设置:

修改后的CSS代码:

body {
background-color: aquamarine;
}
.box {
 height: 120px;
 width: 120px;
 border-radius: 60px;
 background-color: black;
 position: relative; /* 添加相对定位,让left属性生效 */
 }

如果需要在JS中动态设置定位(不推荐,样式尽量统一放在CSS),可以在move函数中添加:

moving.style.position = "relative";

修改后点击.box元素,它会向右偏移10px,同时背景变为白色,功能正常生效。

内容的提问来源于stack exchange,提问作者useless

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:15:39