jQuery 以百分比分配宽度,但希望以像素为单位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17305707/
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
Assigned width in percentage but want to get it in pixels
提问by Denzz
.test {
border: 1px solid;
cursor: pointer;
height: 10px;
position: relative;
width: 100%;
}
<div id="test1" class="test"></div>
I have displayed my HTML id
and its CSS. Now when I am doing $('#test').width()
I am getting 100
. I want its width
in pixels (not in %
).
我已经显示了我的 HTMLid
和它的 CSS。现在,当我这样做时,$('#test').width()
我得到了100
. 我想要它width
的像素(而不是%
)。
Can anyone tell how to get its width in pixels?
谁能告诉如何以像素为单位获得其宽度?
采纳答案by ayyp
.width()
gets "...the current computed width" of the element that is used on, per the jQuery width documentation: http://api.jquery.com/width/, so the return value from $('#heatMapBar').width()
is in pixels, not percent. I would suggest using developers tool to check the width, it may be that in #heatMapBar
's current context, its width is 100px.
.width()
根据 jQuery 宽度文档:http: //api.jquery.com/width/ 获取使用的元素的“...当前计算宽度” ,因此返回值$('#heatMapBar').width()
以像素为单位,而不是百分比。我建议使用开发人员工具检查宽度,可能是在#heatMapBar
当前上下文中,其宽度为 100px。
If you look here: http://jsfiddle.net/NkQXa/1/you will see that #test
is set to width:50%;
, but it alerts the actual pixel width.
如果你看这里:http: //jsfiddle.net/NkQXa/1/你会看到它#test
被设置为width:50%;
,但它会提醒实际的像素宽度。
回答by Jan Jar?ík
One of options can be too, that parent element is not visible. Here is example: http://jsfiddle.net/nDMM3/
选项之一也可以是,该父元素不可见。这是示例:http: //jsfiddle.net/nDMM3/
You can see, that jQuery return width = 100 (like 100%)
你可以看到,jQuery 返回宽度 = 100(比如 100%)
.test {
border: 1px solid;
cursor: pointer;
height: 10px;
position: relative;
width: 100%;
display:none;
}
#test2{
width:100%;
}
<div id="test1" class="test">
<div id="test2">
Hello
</div>
</div>
alert($('#test2').width());
回答by Axel Schmitz
There can be a problem with multiple divs having percentage width:
多个具有百分比宽度的 div 可能存在问题:
<div style="width: 50%">
<div id="getMyWidth" style="width: 100%"></div>
</div>
In this case it returns 100 as width for the inner div for me. I solved it by taking the width of the outer div.
在这种情况下,它为我返回 100 作为内部 div 的宽度。我通过取外部 div 的宽度来解决它。
回答by Kalle
Another solution without jquery is to use the property clientWidth
available on HTMLElements
另一个没有 jquery 的解决方案是使用clientWidth
HTMLElements 上可用的属性
document.getElementById('test1').clientWidth
回答by Peter Darmis
Based on Honzik'sanswer there this is a small workaround in case the element needed to specify it's width is inside a hidden parent element.
根据Honzik 的回答,这是一个小的解决方法,以防需要指定其宽度的元素位于隐藏的父元素内。
function getWidth(elemID) {
// get parent element unique id (must have)
var parentId = $("#"+elemID).parent().prop("id");
// remove the child element based on the specified element id
$("#"+elemID).remove();
// append a new child element but on body where most probably is not set to "display:none"
$("body").append('<div id="'+elemID+'">Hello</div>');
// get the width of the newly appended child element and store it to a variable
var width = $("#test2").width();
// remove child element from body
$("#"+elemID).remove();
// re-append child element to its former position under former parent element (having CSS attribute "display:none")
$(parentId).append('<div id="'+elemID+'">Hello</div>');
// display stored element width
alert(width);
}
// usage to get the element's width
getWidth("test2");
Try it in the below snippet!
在下面的代码片段中尝试一下!
function getWidth(elemID) {
var parentId = $("#"+elemID).parent().prop("id"); // your parent element should have a unique id specified
$("#"+elemID).remove();
$("body").append('<div id="'+elemID+'">Hello</div>');
var width = $("#test2").width();
$("#"+elemID).remove();
$(parentId).append('<div id="'+elemID+'">Hello</div>');
alert(width);
}
getWidth("test2");
.test {
border: 1px solid;
cursor: pointer;
height: 10px;
position: relative;
width: 100%;
display:none;
}
#test2{
width:100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test1" class="test">
<div id="test2">
Hello
</div>
</div>
回答by Matthew Brent
Just an idea...don't hate. I know it doesn't cover every eventuality but something like thiscould check each of the items parents for the desired css rules (display:none; in this case). I got the idea from here.
只是一个想法...不要讨厌。我知道这并不万无一失,但喜欢的事,这样可以检查每个项目的父母所希望的CSS规则(显示:无;在这种情况下)。我从这里得到了这个想法。
The only problem is when a site gets more complicated...it becomes slow.
唯一的问题是当网站变得更复杂时……它变得很慢。
But it's a jumping off point.
但这是一个起点。
//showing as 100%
alert($('#test2').width());
//use window.load to ensure .width() isnt doing anything funny
$(window).load(function(){
//checks to see if any of its parents have display:none; we can have multiple checks here if required
if ($( "#test2" ).parents().css('display') == 'none') {
//iterate through each parent of the selected item
$( "#test2" ).parents().each(function () {
//only change the display value if the element has a display:none;
if ($(this).css('display') == 'none') {
$(this).css('display', 'block');
alert($('#test2').width());//or whatever we want to do with this number
//reset values here
$(this).css('display', 'none');
}
});
}
//showing as 100%
alert($('#test2').width());
});
回答by Pankaj Gautam
I am not sure about this fact but $("#id/.class").width()
gives the value in pixelsin my case.
我不确定这个事实,但在我的例子中$("#id/.class").width()
给出了像素值。
In above screen-shot you can find different values of $("#id/.class").width()
in pixelsat different screen size of browser.
在上面的屏幕截图,你可以找到不同的价值观$("#id/.class").width()
中的像素在浏览器的屏幕大小不同。
Well I'm using Firefox for this purpose.
好吧,我正在为此目的使用 Firefox。
You can also check the jquery documentationon this topic.
您还可以查看有关此主题的jquery 文档。
回答by KickyTrick
Pls check the code appended below, I hope this is the simplest way to get the width from percentage to pixel.
请检查下面附加的代码,我希望这是获得从百分比到像素的宽度的最简单方法。
HTML
HTML
<div id="test1" class="test">
<p id="widthPx"> Perentage to Pixel : </p>
</div>
CSS
CSS
.test {
border: 1px solid;
cursor: pointer;
height: 100%;
position: relative;
width: 100%;
padding: 10px;
}
JS
JS
var widPx = $('#test1').width();
$('#widthPx').append(Math.round(widPx) + 'px');
OUTPUT
输出
Perentage to Pixel : 609px
像素百分比:609px
The output would be purely based on the div width.
输出将完全基于 div 宽度。
Thanks.
谢谢。
回答by Dhruv Ramdev
That can be a co-incidence . According to the official documentation on api.jqery.com, it states that
这可能是一个共同事件。根据api.jqery.com上的官方文档,它指出
Get the current computed width for the first element in the set of matched elements.
获取匹配元素集中第一个元素的当前计算宽度。
To confirm that you are getting the width in pixels , you can equate this value to .css(width) method of jQuery . It returns the width in pixels and hence , you can confirm that the return height is in Pixels.
要确认您获得的宽度是以像素为单位,您可以将此值等同于 jQuery 的 .css(width) 方法。它以像素为单位返回宽度,因此,您可以确认返回高度以像素为单位。
回答by SP193
It could have been a bug in earlier jQuery versions, up to this Github PR: https://github.com/jquery/jquery/pull/3741
它可能是早期 jQuery 版本中的一个错误,直到这个 Github PR:https: //github.com/jquery/jquery/pull/3741
Although it's 2019 now, I had to use jQuery 1.12.4 and noticed that width computation of a hidden (hidden by parent) element was always 100.
尽管现在是 2019 年,但我不得不使用 jQuery 1.12.4 并注意到隐藏(由父级隐藏)元素的宽度计算始终为 100。
By debugging, I found that the jQuery outerWidth (similar for innerHeight, innerWidth, height, width, outerHeight and outerWidth) function will call the width cssHook, which in turn calls getWidthOrHeight(). getWidthOrHeight() may obtain a width in %, which is then returned as it is. The width function does not check what was returned and passes it through parseFloat, which results in the 100% becoming just 100.
通过调试,我发现jQuery的outerWidth(类似于innerHeight、innerWidth、height、width、outerHeight和outerWidth)函数会调用宽度cssHook,而cssHook又会调用getWidthOrHeight()。getWidthOrHeight() 可以获得以 % 为单位的宽度,然后按原样返回。width 函数不检查返回的内容并将其传递给 parseFloat,这导致 100% 变为 100。