Home >Web Front-end >HTML Tutorial >HTML implements code to obtain element size, width and height (pure code)

HTML implements code to obtain element size, width and height (pure code)

不言
不言Original
2018-08-02 10:24:333533browse

This article introduces to you the code (pure code) for obtaining the element size width and height in HTML. It has certain reference value. Friends in need can refer to it. I hope it will be useful to you. Helps.

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>获取元素尺寸宽高</title>
</head>
    <style>
        #div{
            background-color: #00ff00;
            width: 60px;
            height: 60px;
            padding: 20px;
            margin: 20px;
            border: 20px solid #00ffff;
        }
    </style>
<body>
    
    <div id="div">Prosper</div>

    <script>
    /**
     * 获取元素尺寸宽高(不包含margin)
     */
    Element.prototype.getElementOffset = function () {
        var objData = this.getBoundingClientRect();
        if (objData.width) {
            return {
                w: objData.width,
                h: objData.height
            }
        } else {
            return {
                w: objData.right - objData.left,
                h: objData.top - objData.bottom
            }
        }
    }
    console.log(document.getElementById(&#39;div&#39;).getElementOffset());
    </script>
</body>

</html>

Related recommendations:

htmlGiven tag options and add tags (with code)

HTML Implementation of obtaining the width and height of the browser's visible area (pure code)

html Implementation of obtaining the browser scrolling distance (pure code)

The above is the detailed content of HTML implements code to obtain element size, width and height (pure code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn