javascript - 一个关于offsetLeft的纠结的小问题

查看:123
本文介绍了javascript - 一个关于offsetLeft的纠结的小问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>offsetleft</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background: grey;
            position: absolute
        }

        body {
            position: relative;
        }
    </style>
</head>

<body>
    <div id="div01"></div>
</body>

</html>
<script>
    var div01 = document.getElementById("div01");
    console.log(div01.offsetParent)
    console.log(div01.offsetLeft)
    //使用的是360浏览器
</script>

在有 body{position:relative;} 的情况下:div01.offsetLeft 输出为0,在没有body{position:relative;} 的情况下,div01.offsetLeft 输出为8,他们div01.offsetParent 输出都是body,多出的 8px 是什么原因导致的呢?(估计是body的margin:8px)但是 offsetParent 是到父级的内边框的距离额

解决方案

offsetParent 还是一个草案,所以存在一些问题也正常。从 MDN 上来看只清楚 Chrome 和 Edge 实现了,我尝试了一下两个浏览器,结果是一样的。

然后输入 document.body.offsetParentdocument.body.parent 来看,一个是 null 一个是 undefined,说明这里页面的根元素就是 body

然后文档中提到一个东西叫 "positioned element",这个概念没找到官方解释,所以不是很清楚。不过从实验的结果来看,不管一个 div 如果设置 displayposition,它都可以是 offsetParent,而 span 则是 non-positioned

换句话说,如果把 container 换成 spanoffsetParent 是取不到它的,取到的是它的上一级元素 body。但是 offsetLeft 计算出来却是 body 的 marginLeft + span 的 marginLeft + span.paddingLeft。从这个现象可以推算出,虽然根级 offsetParent 指向 body,但在实际从根级元素计算 offsetLeft 的时候,是从 <html> 开始算的。

虽然有点不好理解,但实验结果如此——我觉得还是等草案成熟吧。而且也不一定非要用这种方法来获取位置信息。

下面是我修改出来的实验代码(HTML)

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>offsetleft</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            background: grey;
            position: absolute
        }

        body {
            /* position: relative; */
        }

        .container {
            position: relative;
        }

        .container2 {
            display: block;
            margin: 4px;
            padding: 10px;
        }
    </style>
</head>

<body>
    <div id="div00"></div>
    <div class="container">
        <div id="div01"></div>
    </div>
    <span class="container2">
        <div id="div02"></div>
    </span>
</body>

</html>
<script>
    function print(el) {
        console.log("offsetParent", el.offsetParent)
        console.log("offsetLet", el.offsetLeft)
    }

    console.log("body.parent", document.body.offsetParent);
    console.log("body.parent", document.body.parent);
    console.log("body padding: ", document.body.style.padding);

    print(document.getElementById("div00"));
    print(document.getElementById("div01"));
    print(document.getElementById("div02"));

</script>

以及结果 (Chrome 53)

这篇关于javascript - 一个关于offsetLeft的纠结的小问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆