[英]Element width in chrome using jquery
I need element width before appending to body. 在追加到body之前我需要元素宽度。
Following scripts is working fine in firefox
but not in google chrome
以下脚本在
firefox
运行良好,但在google chrome
没有
<style>
.testDiv { width:150px; height:100px; }
</style>
<script>
var div = "<div class='testDiv'>Div Content</div>";
alert($(div).width());
</script>
It gives output 150
in firefox and 0
in chrome 它在firefox中提供输出
150
,在chrome中提供0
I have tried also 我也试过了
$(window).load(
function() {
alert($(div).width());
}
);
But it is working same... 但它的工作原理相同......
UPDATE: 更新:
I can see, if I declare css inline
it works but it is needed to me using css class
我可以看到,如果我声明
css inline
它可以工作,但我需要使用css class
var div = "<div style='width:150px;'>Div Content </div>";
alert($(div).width());
This may be the reason , if you have in-line css in your div say, it will display your width properly. 这可能是原因,如果你的div中有内嵌css,它会正确显示你的宽度。 probably css properties does not load in chrome
可能css属性不会加载chrome
<script>
var div = "<div style='width:150px' class='testDiv'>Div Content</div>";
$(window).load(
function() {
alert($(div).width());
}
);
</script>
I think you can't do that in Chrome and I'm sure there is a good explanation but I don't know it. 我认为你不能在Chrome中这样做,我确信有一个很好的解释,但我不知道。 So here is my solution to that problem jsFiddle Append a div to the DOM with
display:none
and when you have the width remove it. 所以这是我对该问题的解决方案jsFiddle使用
display:none
将DOM附加到DOM,当你有宽度时将其删除。 The answer which @lampdev gave is also correct but it takes just the width from the style attribute. @lampdev给出的答案也是正确的,但它只需要style属性的宽度。 That is not the computed width and it will be wrong in many cases.
这不是计算出的宽度,在许多情况下都是错误的。
You could try something like this: 你可以尝试这样的事情:
var div = "<div class='testDiv'>Content</div>";
$(div).attr('id', 'test').css('position', 'fixed').appendTo('body');
console.log($("#test").width());
$("#test").remove();
This will give you the width without crashing your view and your div variable will still have the correct properties. 这将为您提供宽度而不会使视图崩溃,您的div变量仍将具有正确的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.