javascript 使用 jQuery 以百分比 % 获取 html 元素的宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10624368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the width of an html element in percent % with jQuery
提问by vitto
If I alert
the element which has a css selector set to width:100%
I get it's with in px
, is there some way to get it in %
as set from css, I need it to fix some script with fluid layouts.
如果我alert
将 css 选择器设置为width:100%
使用 in的元素px
,是否有某种方法可以将它%
从 css 设置为设置,我需要它来修复一些具有流体布局的脚本。
// css
.my-element {
width:100%;
}
// javascript
alert('width: '+$('.my-element').css('width'));
// this alerts "width: 1116px" instead of "width: 100%"
Maybe something like this is always true?
也许这样的事情总是正确的?
alert($('.my-element').outerWidth() == $('.my-element').parent().outerWidth());
回答by kennebec
function percentwidth(elem){
var pa= elem.offsetParent || elem;
return ((elem.offsetWidth/pa.offsetWidth)*100).toFixed(2)+'%';
}
回答by Adil
You can get the width in percentage by two methods.
您可以通过两种方法以百分比形式获取宽度。
With jQuery use jQuery 1.3.2 and you will get 100%.
使用 jQuery 使用 jQuery 1.3.2,您将获得 100%。
alert($('.my-element').css('width'))?;
With javascript by setting width in style attribute of the tag like this
使用javascript通过在标签的样式属性中设置宽度像这样
<div id="div2" style="width:100%"></div>
div2 = document.getElementById('div2');
alert("Width of div2 with style = " + div2.style.width);