检测真正的边框,填充和边距从Javascript [英] detecting true border, padding and margin from Javascript

查看:142
本文介绍了检测真正的边框,填充和边距从Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从Javascript代码中检测元素的真正边框,填充和边距?如果你看下面的代码:

Is there a way to detect the true border, padding and margin of elements from Javascript code? If you look at the following code:

<html>
    <head>
        <style>
        <!--
        .some_class {
            padding-left: 2px;
            border: 2px solid green;
        }   
        -->
        </style>
        <script>
        <!--
        function showDetails()
        {
            var elem = document.getElementById("my_div");
            alert("elem.className=" + elem.className);
            alert("elem.style.padding=" + elem.style.padding);
            alert("elem.style.paddingLeft=" + elem.style.paddingLeft);
            alert("elem.style.margin=" + elem.style.margin);
            alert("elem.style.marginLeft=" + elem.style.marginLeft);
            alert("elem.style.border=" + elem.style.border);
            alert("elem.style.borderLeft=" + elem.style.borderLeft);
        }
        -->
        </script>
    </head>
    <body>
        <div id="my_div" class="some_class" style="width: 300px; height: 300px; margin-left: 4px;">
            some text here
        </div>
        <button onclick="showDetails();">show details</button>
    </body>
</html>

你可以看到,如果你点击按钮,填充不正确。只有通过style直接定义的属性才会返回,通过CSS类定义的属性不会被报告。

you can see, if you click the button, that the padding is not reported right. Only the properties defined directly through "style" are reported back, those defined through a CSS class are not reported.

有没有办法找回这些属性?

Is there a way to get back the final values of these properties? I mean the values obtained after all CSS settings are computed and applied by the browser.

推荐答案

这是可能的,但当然,每一个浏览器有自己的实现。幸运的是,PPK为我们做了所有的辛勤工作:

It's possible, but of course, every browser has its own implementation. Luckily, PPK has done all the hard work for us:

http://www.quirksmode.org/dom/getstyles.html

这篇关于检测真正的边框,填充和边距从Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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