【问题标题】:Setting Div Width Intelligently智能设置div宽度
【发布时间】:2023-03-23 05:55:01
【问题描述】:

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

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

【问题讨论】:

  • 你可以用min-widthmax-width做点什么...
  • 文本布局是否有预先确定的规则?
  • 根据 Andrew 的建议快速调整一下:jsfiddle.net/DXvXy.
  • 你到底想做什么?使
    具有特定的形状? (黄金比例?正方形?)
  • 在没有解释或您尝试过的情况下说“我该怎么做”的问题很难给出有意义的答案。最简单的解决方案,根据字数使用脚本设置宽度,并在内容更改时再次调用相同的函数。您要么必须控制所有可以更新内容的代码,要么必须轮询 div 以了解内容更改

标签: javascript jquery css layout html


【解决方案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 );
    });
}

【讨论】:

  • 某种解释会很棒。只是说。
  • 添加了一些解释:)
  • -1 我无法弄清楚这与问题有何关系。 OP 正在根据 DIV 中的单词数询问 div 宽度。
  • 抱歉,我还是看不出这段代码有什么用处。您的代码根据鼠标位置改变高度,对我来说看起来不是很吸引人;框外有很多文字。
猜你喜欢
相关资源
最近更新 更多
热门标签