gpt4 book ai didi

javascript - 智能设置 Div 宽度

转载 作者:太空宇宙 更新时间:2023-11-03 19:34:46 24 4
gpt4 key购买 nike

一段时间以来,我一直在尝试寻找一种方法来设置 <div> 的宽度。根据其内容以一种有吸引力的方式。我希望能够告诉 <div>根据段落中的字数,每隔一段时间换行一次。因此,例如,如果它是一个包含 300 个单词的长段落,那么宽度为 500px 并拆分成任意多行,但如果它是 10 个单词,则它只有 100px 宽,并且拆分成两行?

我并不迫切需要它,但我已经放弃了谷歌搜索,并且很好奇这里的任何人是否有任何想法。

最佳答案

也许您可以使用这个小脚本(垂直移动鼠标)。它最初是很久以前用 ActionScript2 编写的。

http://jsfiddle.net/DXvXy/3/

/*
outerNode : block element with a helper wrapper element inside
Fiddles with the width of outerNode until it reaches desired height (maxH)
Width is limited between minW and maxW
*/
var fitToHeight = function( outerNode, minW, maxW, maxH ){
var L,H,A; // Lo,Hi,Actual width for binary search
var $set = $(outerNode); // new width will be applied to the outer node
var $get = $($set).children(); // actual width / height readout

// Set initial width to the longest non-wrapping word (
$set.width( minW );
L = H = Math.min( maxW, Math.max( minW, $get.width())); // longest word

// grow the width until height falls below maxH
while( $get.height() > maxH && H < maxW ){
// remember the width of the last too high box: it will be the lower limit for bin.search
L = H;
H = Math.min( H*2, maxW ); // limited grow of upper limit
$set.width( H );
}
H = Math.min( maxW, $get.width() );

// binary search for the ideal width where height just falls below maxH
do{
A = Math.round( ( H + L )/2 );
$set.width( A );
if( $get.height() > maxH ) L=A; else H=A;
}while( H - L > 1 );

// width might be smaller by a subpixel, so increment it to guarantee maximum height
if( $get.height() > maxH )
$set.width( A+1 );

// set block's height if necessary
$set.height( maxH );
};


jQuery.fn.fitToHeight = function( minW, maxW, maxH ){
this.each(function(){
fitToHeight( this, minW, maxW, maxH );
});
}

关于javascript - 智能设置 Div 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11036716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com