[英]How to get width and height of text not the span with display table-cell
[英]Chrome 30 and the width of elements of type display: table-cell?
我在使用最新的測試版Chrome(30.0.1599.14測試版)時遇到問題。
我無法計算類型為display的元素的真實寬度:table-cell。
這是一些測試代碼,它們在調整瀏覽器窗口大小時將表格單元的寬度輸出到控制台:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.table {
background: #ffc;
display: table;
width: 100%;
}
.cell {
display: table-cell;
width: 200px;
border: 1px solid black;
background: #ff0;
height: 30px;
}
#testCell {
background: #f00;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).on( "ready", function() {
$(window).on( "resize", function() {
var width = document.getElementById( "testCell" ).offsetWidth;
// non jQuery way, for testing:
// var width = document.getElementById( "testCell" ).offsetWidth;
console.log( width );
});
});
</script>
</head>
<body>
<div class="table">
<div class="cell" id="testCell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell"></div>
<div class="cell" ></div>
</div>
</body>
</html>
在Safari和Firefox的最新版本以及Chrome 29中,該功能均能正常運行。 也就是說,即使寬度是在css中設置的,因為它是一個表格單元元素,所以實際的寬度是填充父表格元素的任何寬度。 因此,值將隨着調整瀏覽器窗口的大小而改變。
但是,在Chrome 30中,即使可以正確渲染,輸出到控制台的寬度也始終是css值:200。
對於我的某些腳本來說,這是一個問題,這些腳本需要為布局目的計算表單元格的真實寬度。
您有什么想法嗎?如何在Chrome 30中使用它?
編輯:
好的,我找到了解決方法。 clientWidth仍然可以按預期工作,因此可以通過以下方式計算寬度:
var width = document.getElementById( "testCell" ).clientWidth;
...會做的工作。 但是,如果有人知道信息,我仍然想知道這里發生了什么。
謝謝!
我有類似的問題。
我認為問題出在chrome 30中。
請參閱https://code.google.com/p/chromium/issues/detail?id=290399 。
關於此的另一篇文章在這里: 計算寬度在Chrome中錯誤,在FFox / IE中可以嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.