[英]How to get the maximum possible width of a div?
我需要知道如何獲得div的最大可能寬度。 通常, <div>
的寬度受其父級限制,這意味着它不能大於一定的數量。 如何計算一定的金額?
我需要它來計算當前<div>
的文本是否溢出(因為檢測文本溢出的唯一方法是將其當前寬度與其當前的clientWidth進行比較)。
謝謝!
幾種方法可以做到這一點,讓我們從您的部門開始...
<div id='mr_cleaver'>
<div id='beaver'>Blah</div>
</div>
...然后是一些Javascript:
//Method One: Find the width of the div's parent
var max_beaver_width = $('mr_cleaver').offsetWidth
//Method Two: Max out the div, find length, return to original size.
var beaver_width = $('beaver').offsetWidth;
$('beaver').style.width = "100%";
var max_beaver_width = $('beaver').offsetWidth;
$('beaver').style.width = beaver_width + 'px';
//Method Three: Check for overflow
$('beaver').scrollWidth > $('beaver').offsetWidth ? alert("Over") : alert("Within")
如果您希望div的寬度為100%,並且邊緣之間沒有空格,則可以嘗試將此simpel CSS樣式添加到div中:
<style type="text/css">
#FullWidthDiv { // EDIT
position: absolute; // If you use 'fixed' as position, then the div
display: block; // won't become smaller when the screen is at is smallest.
float: left; // The fixed position is good when you for example want the
width: 100%; // menu to stay in place.
background-color: #06F;
height: auto;
left: 0px;
top: 0px
}
</style>
<html>
<body>
<div id="FullWidthDiv"></div>
</body>
</html>
您可以將div附加到父元素中以對其進行度量。
var test = document.querySelector('#test'); var div = document.createElement('div'); div.style.width = '10000px'; test.appendChild(div); var maxWidth = test.offsetWidth; test.removeChild(div); alert(maxWidth);
#test { display: inline-block; max-width: 100px; }
<div id="test"></div>
謝謝史蒂夫!
您的建議非常有幫助。 盡管它們都不對我有用(可能我沒有很好地解釋我的情況),但是使用您的提示,我可以找到一種檢測文本溢出的方法:
/* specifying the height of 'beaver'*/
var font_size= $('beaver').css("font-size");
font_size = parseInt(font_size.replace(/[a-z]*/gi,''));
var maxHeight = font_size + 4; // 4 is to make sure that the font fits in the maxHeight
/*now calculate current height*/
$('beaver').style.overflow-y:visible;
$('beaver').style.overflow-x:hidden;
var cuurentHeight = $('beaver').clientHeigth;
/* check whether overflow is occured*/
if(cuurentHeight > maxHeight){
//overflow has been occured
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.