是否有可能跨越多行的宽度收缩包装内容? [英] Is it possible to width-wise shrink-wrap content that spans more than one line?

查看:93
本文介绍了是否有可能跨越多行的宽度收缩包装内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含在框中的元素:

If I have an element contained in a box:

+-------- box --------+
| *------------*      |
| | small text |      |
| *------------*      |
+---------------------+

display:inline-block 做收缩包装的窍门。但是,如果由于约束宽度,内容跨越多行,则它无法收缩包装元素。

display: inline-block does the trick of shrink-wrapping it just fine. However, if the content spans more than one line because of the constrained width, it fails to shrink-wrap the element.

+-------- box --------+
| *-----------------* |
| | this does not   | |
| | shrink          | |
| | appropriately   | |
| *-----------------* |
+---------------------+

有没有任何方法可以产生如下所示的期望结果?

Is there any way of producing the desired result seen below?

+-------- box --------+
| *---------------*   |
| | this does not |   |
| | shrink        |   |
| | appropriately |   |
| *---------------*   |
+---------------------+

下面是一个显示两种情况的小提示: http://jsfiddle.net/urLa8jvc/2/ 和一个解决方案,我手动在正确的地方打破行显示所需的结果。
首选CSS解决方案,但也可以使用javascript。

Here is a fiddle showing the two cases: http://jsfiddle.net/urLa8jvc/2/ and a solution where I manually break the line at the correct place to show the desired outcome. A CSS solution is preferred, but javascript is also acceptable.

推荐答案

是CSS,但现在我写了这个黑客使用javascript:窍门: http:// jsfiddle .net / 86khx8kf / 2 /

I'd really much prefer the solution to be CSS, but for now I've written this "hack" that does the trick using javascript: http://jsfiddle.net/86khx8kf/2/

var nodes = document.querySelectorAll(".node");
for (var nidx = 0; nidx < nodes.length; nidx++) {
    var node = nodes[nidx];
    node.innerHTML = node.innerHTML.split(" ").map(function (word) {
        return "<span>" + word + "</span>";
    }).join(" ");
    var spans = node.querySelectorAll("span");
    var offsetLeft = -Number.MAX_VALUE;
    for (var sidx = 0; sidx < spans.length; sidx++) {
        var span = spans[sidx];
        if (span.offsetLeft <= offsetLeft) {
            node.insertBefore(document.createElement("br"), span);
        }
        offsetLeft = span.offsetLeft;
        span.outerHTML = span.innerHTML;
    }
    node.normalize();
}

这篇关于是否有可能跨越多行的宽度收缩包装内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆