1

For a while, I have been trying to find a way to set the width of a <div> according to its content in an attractive way. I want to be able to tell the <div> to have a line break every so often, according to how many words are in the paragraph. So for example, if it's a long paragraph with 300 words, then the width is 500px and split over however many lines, but if it's 10 words, it's only 100px wide, and split over two?

I don't desperately need it but I have given up googling and was curious if anybody around here had any ideas.

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 に答える