Element.scrollWidth - Web APIs 编辑

The Element.scrollWidth read-only property is a measurement of the width of an element's content, including content not visible on the screen due to overflow.

The scrollWidth value is equal to the minimum width the element would require in order to fit all the content in the viewport without using a horizontal scrollbar. The width is measured in the same way as clientWidth: it includes the element's padding, but not its border, margin or vertical scrollbar (if present). It can also include the width of pseudo-elements such as ::before or ::after. If the element's content can fit without a need for horizontal scrollbar, its scrollWidth is equal to clientWidth

This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect().

Syntax

var xScrollWidth = element.scrollWidth;

xScrollWidth is the width of the content of element in pixels.

Example

<!DOCTYPE html>
<html>
<head>
    <title>Example</title>
    <style>
        div {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
        }

        #aDiv {
            width: 100px;
        }

        button {
            margin-bottom: 2em;
        }
    </style>
</head>

<body>
    <div id="aDiv">
        FooBar-FooBar-FooBar-FooBar
    </div>
    <button id="aButton">
        Check for overflow
    </button>

    <div id="anotherDiv">
        FooBar-FooBar-FooBar-FooBar
    </div>
    <button id="anotherButton">
        Check for overflow
    </button>
</body>
<script>
    var buttonOne = document.getElementById('aButton'),
    buttonTwo = document.getElementById('anotherButton'),
    divOne = document.getElementById('aDiv'),
    divTwo = document.getElementById('anotherDiv');

    //check to determine if an overflow is happening
    function isOverflowing(element) {
        return (element.scrollWidth > element.offsetWidth);
    }

    function alertOverflow(element) {
        if (isOverflowing(element)) {
            alert('Contents are overflowing the container.');
        } else {
            alert('No overflows!');
        }
    }

    buttonOne.addEventListener('click', function() {
        alertOverflow(divOne);
    });

    buttonTwo.addEventListener('click', function() {
        alertOverflow(divTwo);
    });
</script>
</html>

Result

Specifications

SpecificationStatusComment
CSS Object Model (CSSOM) View Module
The definition of 'Element.scrollWidth' in that specification.
Working DraftInitial definition

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:78 次

字数:4837

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文