如何查找或检测div内的文本是否溢出,我可以减少字体大小,以便文本内容完全适合div。 div with overflow
.c{
width:30px;
height:30px;
background-color:red;
border-radius:100%;
position:absolute;
text-align:center;
line-height:30px;
}
现在如何使用jquery.Thanks
找到它答案 0 :(得分:2)
试试这个:
var c;
var max_height;
var current_height;
var current_font_size;
function fitFontSize(){
current_height = c.height();
current_font_size = parseInt( c.css("font-size") );
if(current_height > max_height){
console.log("Overflow!")
current_font_size --;
c.css("font-size" , current_font_size+"px") ;
fitFontSize();
}
}
$(function(){
c = $(".c");
max_height = parseInt( c.css("min-height") );
fitFontSize();
});
诀窍是使用min-height
代替height
。
JSFiddle:http://jsfiddle.net/dpQ9t/2/
答案 1 :(得分:0)
我想解决方案就是想出这样的问题:
显然,圆圈代表你的外部div,方形代表里面的文字。我写了一些jQuery函数来完成你想要的。
这是JSfiddle。希望它有所帮助。
现在解释一下,
首先,我们将所有文本放在内部div中。这是为了确保我们能够正确计算高度和宽度。
<div class="circle">
<div class="text">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta, quisquam, mollitia, dolores sit accusamus molestiae necessitatibus rerum nisi natus itaque amet maiores tempore veniam qui aut ullam odio magnam quidem!
</div>
</div>
我们还确保通过设置box-sizing
.circle .text {
border: 1px solid #bbb;
background: #fff;
font-size: 16px;
/* This box sizing is necessary for inner calculations */
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 5px;
}
最后,如果文本div高度大于计算出的方边长度,我们将javascript用于计算字体大小属性。否则,我们只需调整边距使其显示在中心位置。
$('.circle').each(function() {
//Get the container and inner text
var circle = $(this),
text = $(this).find('>.text');
//Get some variables
var height = circle.height(),
width = circle.width(),
radius = 0,
sideLength = 0,
margin = 0,
fontSize = 0;
//Fix it if necessary
if(height !== width) {
radius = Math.round(parseFloat(Math.max(height, width) / 2, 10));
circle.height(radius * 2).width(radius * 2);
} else {
radius = Math.round(height / 2);
}
//Now calculate a square box inside the circle to put the text into
//This is pure maths
//The diagonal of the square is basically two times of the radius
//Which means side is approximately radius * 1.4142
sideLength = Math.round(radius * 1.4142);
//Thus calculate the margin
margin = ( height - sideLength ) / 2;
//Assign the width
text.css('width', sideLength);
//Assign the margin
text.css({
'margin-left' : margin,
'margin-top' : margin
});
//lets center the text if it's height is less than sideLenght
if(text.height() < sideLength) {
var newMarginTop = (height - text.height()) / 2;
text.css('margin-top', newMarginTop);
} else if(text.height() > sideLength) { //Or adjust the font
//Now keep on decreasing the font until the height of the text becomes
//less than or equal to the calculated size
while(text.height() > sideLength) {
fontSize = parseInt(text.css('font-size'), 10);
text.css('font-size', --fontSize);
}
}
});
希望我能解释一下。如果你什么都不懂,请告诉我。