Home  >  Article  >  Web Front-end  >  How to get the scroll bar width in js (code example)

How to get the scroll bar width in js (code example)

不言
不言Original
2018-08-11 15:49:003038browse

The content of this article is about how to obtain the scroll bar width in js (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Idea: By creating an element, do not set a border for the element, then set overflowY:scroll for the element, and then calculate the scroll bar width based on the element's offsetWidth-clientWidth.

Code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>计算滚动条宽度</title>
</head>

<body>
    <script>
        // 封装获取滚动条宽度的方法
        function getScrollBarWidth() {
            var el = document.createElement("p"),
                styles = {
                    width: "100px",
                    height: "100px",
                    overflowY: "scroll"
                },
                i;

            // 这里很巧妙呀,先定义了一个styles对象,里面写了各种样式值,然后通过for in将这个对象的值赋给p元素的style对象
            // 而不用通过style.width=***等来给p的样式对象赋值。
            for (i in styles) {
                el.style[i] = styles[i];
            }

            // 将元素加到body里面
            document.body.appendChild(el);

            var scrollBarWidth = el.offsetWidth - el.clientWidth;
            //将添加的元素删除
            el.remove();
            return scrollBarWidth;
        }

        console.log(getScrollBarWidth()); // 注意这里imac得到的结果为0,因为imac的滚动条是没有宽度的。
    </script>
</body>

</html>

Related recommendations:

What are the implementation methods of JS modularization? Explanation of js modularization

#How to write css animation in js? How to write css animation in js (code)

The above is the detailed content of How to get the scroll bar width in js (code example). 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