CSS - 很好的方法来做“步进”文本? [英] CSS - Nice way to do 'stepped' text?

查看:102
本文介绍了CSS - 很好的方法来做“步进”文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个很好的方式实现以下,没有任何额外的标记?

Is there a nice way of achieving the following, without any additional mark-up? It would be fine to use JavaScript though.

有任何想法吗?

谢谢!

编辑:

我的标记将类似于:

<div style="width: 400px;">
  <p>Text text text Text text text Text text text</p>
</div> 


推荐答案

对于给定的文本元素,找到第一行的结尾,然后将剩余的文本包装在子div中。

For a given element of text, use a text range to find the end of the first line, then wrap the remaining text in a child div. Repeat recursively, using the child div for the next iteration.

这可以跨浏览器工作: http://jsfiddle.net/gilly3/CmguZ/4/

This works cross-browser: http://jsfiddle.net/gilly3/CmguZ/4/

这是最简单的IE感谢 textRange.moveToPoint(x,y)

It's easiest in IE thanks to textRange.moveToPoint(x, y):

function indent(div) {
    var rng = document.body.createTextRange();
    rng.moveToElementText(div);
    var x = rng.getBoundingClientRect().right;
    rng.collapse();
    var rect = rng.getBoundingClientRect();
    var y = rect.bottom;
    rng.moveToPoint(x - 1, y - 1);
    rng.moveEnd("textedit");
    var html = "<div class=\"indent\">" + rng.text + "</div>";
    rng.pasteHTML(html);
    div = $(".indent", div)[0];
    rng.moveToElementText(div);
    var pos = rng.getBoundingClientRect();
    if (pos.bottom > rect.bottom) {
        indent(div);
    }
}

对于其他浏览器,找到行包装的位置:

With other browsers, you have to iterate the text to find where the line wraps:

function indent(div) {
    var rng = document.createRange();
    rng.selectNodeContents(div);
    var len = rng.toString().length;
    var start = rng.toString().search(/.\s/);
    if (start < 0) return;
    var txt = div.childNodes[0];
    rng.setEnd(txt, start);
    var startRect = rng.getBoundingClientRect();
    var rect;
    for (var i = start + 1; i < len; i++) {
        rng.setEnd(txt, i);
        rect = rng.getBoundingClientRect();
        if (rect.bottom > startRect.bottom) {
            rng.setStart(txt, i-1);
            rng.setEnd(txt, len);
            div = document.createElement("div");
            div.className = "indent";
            rng.surroundContents(div);
            indent(div);
            break;
        }
    }
}

这篇关于CSS - 很好的方法来做“步进”文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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