如何使用 Javascript 获取 CSS 宽度值?
我正在尝试计算元素的宽度,以便当我使用 JavaScript 将父元素包裹在其周围时,我可以将父元素的宽度设置为与子元素的宽度相匹配。明显的 $('#element').css('width');
并不完全是我想要的,因为它似乎只返回以像素为单位的计算值。有什么方法可以返回实际的 CSS 值(无论是 300px
或 20%
或 auto
),而不是计算值?
一般情况下是这样设置的,但我想知道 #child
的 CSS 值而不是计算值。
$(document).ready(function(){
$('#child').wrap('<div id="parent"></div>');
$('#parent').each(function(){
var childWidth = $(this).children('#child').css('width');
$(this).css('width', childWidth)
});
});
I'm trying to calculate the width of an element so that when I use JavaScript to wrap a parent element around it, I can set the width of the parent to match the width of the child. The obvious $('#element').css('width');
isn't quite what I want because it only seems to return the calculated value in pixels. Is there some way that I can return the actual CSS value, whether it be 300px
or 20%
or auto
, instead of the calculated value?
Here's generally how it's set up, but I'd like to know the CSS value of #child
instead of the calculated value.
$(document).ready(function(){
$('#child').wrap('<div id="parent"></div>');
$('#parent').each(function(){
var childWidth = $(this).children('#child').css('width');
$(this).css('width', childWidth)
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不相信你能做到这一点。最好的结果是 offsetWidth 或 clientWidth,它们返回计算值,包括或不包括边距、填充和边框。
I don't believe you can do that. The best you will get is offsetWidth or clientWidth which return the calculated value, with and without counting margins, padding and borders.
您需要阅读样式表本身。
请参阅:如何通过 Javascript 读取样式表中定义的 CSS 文本?
You need to read the stylesheet itself.
See: How can I read out the CSS text via Javascript as defined in the stylesheet?
除了 IE 之外,每个人都支持
window.getComputedStyle(element)
,您可以像这样使用它:不过,对 IE 没有帮助。
Everyone but IE supports
window.getComputedStyle(element)
, which you can use like so:Doesn't help you with IE, though.