踩坑记录:left&offsetLeft的区别

本文探讨了使用CSS百分比进行元素定位时遇到的问题,特别是当元素位置使用50%时,offsetLeft和style.left返回值的不一致,以及在尝试实现鼠标拖拽效果时出现的抖动现象。通过对比具体数值定位,揭示了offset系列属性在处理百分比时的内部机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇文章说的很详细。
https://www.cnblogs.com/agansj/p/7225256.html

在这里插入图片描述
为元素添加top:50%; 百分比数值的时候style.left返回的也是空字符串。

.dialog {
      width: 200px;
      height: 200px;
      background-color: lightsalmon;
      position: absolute;
      left: 50%;	/* 设置50%*/
      top: 50%;
      margin-left: -100px;
      margin-top: -100px;
}

在这里插入图片描述

定位使用百分比的时候offsetLeft也会出现问题。
在这里插入图片描述
获取的数值总比实际数值小

在这里插入图片描述


这是因为这个原因,本想做一个鼠标拖拽移动的效果,通过记录元素的初始offsetLeft值实现,每次都会产生抖动

.dialog {
            width: 200px;
            height: 200px;
            background-color: lightsalmon;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -100px;
            margin-top: -100px;
        }
    dialog.addEventListener('mousedown', (e) => {
        e.preventDefault();
        isDown = true;

        // get Dialog offset
        offset[0] = dialog.offsetLeft;
        offset[1] = dialog.offsetTop;
        console.log("offsetLeft:" + offset[0]);
        console.log("style.left:" + dialog.style.left);

        // mouse initial position
        mouseLastPosition[0] = e.clientX;
        mouseLastPosition[1] = e.clientY;
    }, true);

在这里插入图片描述

改成具体数值

.dialog {
     width: 200px;
     height: 200px;
     background-color: lightsalmon;
     position: absolute;
     left: 200px;
     top: 200px;
 }

因为不是写在内联属性style里,所以style还是获取不到。
在这里插入图片描述

拖动以后设置了style.left(这里就不贴代码了,脑补一下)
但是可以发现设置了实际数值以后,offsetLeftstyle.left没有偏差了。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值