JavaScript样式属性为空 [英] JavaScript style property is empty

查看:102
本文介绍了JavaScript样式属性为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算元素边框的宽度.如果我通过CSS对其进行了显式设置,则可以通过以下方式在JavaScript中进行访问:

I need to calculate the width of an element's border. If I set it explicitly (via CSS), then I can access it in JavaScript by:

    element.style.borderWidth

但是,如果仅 指定边框样式属性(而不是'border-width')->

However, if only specify border style property (and not 'border-width') ->

    border-style: solid

然后borderWidth属性为空.为什么?我计算宽度的方法如下:

Then the borderWidth property is empty. Why? My approach to calculate width is as follows:

if(element.style.borderWidth == ''){
    borderWidth = (offsetHeight - clientHeight)/2
}

仅设置border-style时,还有其他方法可以计算边框宽度吗?

Is there any other way to calculate border width whilst only setting border-style?

推荐答案

您可以将window.getComputedStyle用于现代浏览器

You can use the window.getComputedStyle for modern browsers

window.getComputedStyle(element).borderBottomWidth;


对于IE 9之前的版本,您将不得不使用替代方法


For IE pre-9 you will have to use an alternative

element.currentStyle.borderBottomWidth 

这篇关于JavaScript样式属性为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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