HTML offsetwidth

时间:2013-11-07 02:00:12

标签: javascript offsetwidth

有人可以列出构成offsetwidth的属性吗?

另外,我需要计算offsetwidth,通过javascript检索所有这些属性并总结它们。所有这些属性的总和必须等于offsetwidth

代码需要与IE7兼容。

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分:2)

您需要一种方法来确定浏览器的滚动条宽度

// adapted from http://davidwalsh.name/detect-scrollbar-width
function getScrollBarWidth() {
    var container = document.createElement('div');
    container.style.width = '100px';
    container.style.height = '100px';
    container.style.overflow = 'scroll';
    container.style.position = 'absolute';
    container.style.top = '-9999px';
    document.body.appendChild(container);
    var width = container.offsetWidth - container.clientWidth;
    document.body.removeChild(container);
    return width;
}

你还需要一种方法来确定元素是否有一个正确的滚动条,然后你只需要加上所有的宽度!

function getOffsetWidth(element) {
    var hasVerticalScrollbar = element.scrollHeight > element.clientHeight &&
        !(element.style.overflow && element.style.overflow == 'hidden');

    var style = getComputedStyle(element);

    var offsetWidth = (parseFloat(style.getPropertyValue('border-left-width'))) +
        (parseFloat(style.getPropertyValue('border-right-width'))) +
        element.clientWidth +
        (hasVerticalScrollbar ? getScrollBarWidth() : 0);

    return offsetWidth;
}

以下是IE7 / 8中window.getComputedStyle的填充 - http://snipplr.com/view/13523/

这是一个有效的jsbin - http://jsbin.com/iboharI/1/edit?html,css,js,console,output

参考

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetWidth https://developer.mozilla.org/en-US/docs/Determining_the_dimensions_of_elements http://caniuse.com/getcomputedstyle

相关问题