1

一段时间以来,我一直在尝试找到一种方法,以<div>一种有吸引力的方式根据其内容设置 a 的宽度。我希望能够<div>根据段落中有多少单词,每隔一段时间告诉他们换行。例如,如果是一个 300 字的长段落,那么宽度是 500 像素,并且分成多少行,但如果是 10 个字,它只有 100 像素宽,并且分成两行?

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

4

1 回答 1

-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 );
    });
}

​</p>

于 2012-06-14T19:06:20.793 回答