智能地设置Div宽度

时间:2012-06-14 15:46:02

标签: javascript jquery css layout html

有一段时间,我一直试图找到一种方法,以一种有吸引力的方式根据其内容设置<div>的宽度。我希望能够告诉<div>每隔一段时间换一次换行符,根据段落中有多少单词。所以例如,如果它是一个300字的长段,则宽度为500px并分割为多行,但如果它是10个字,则它只有100px宽,并且分成两个?

我并不急需它,但我放弃了谷歌搜索,如果周围的人有任何想法,我很好奇。

1 个答案:

答案 0 :(得分:-1)

也许你可以使用这个小脚本(垂直移动鼠标)。它最初是在很久以前用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 );
    });
}