簡體   English   中英

如何確定HTML元素文本中“新行”的位置?

[英]How can I determine the positions of “new lines” in the text of an HTML element?

在HTML元素(如DIV)中添加長文本時,該元素會包裝該文本。 實際上,正好像這個問題文本一樣。 如何從這樣的HTML元素中獲取文本並確定它在哪里中斷? 即插入新行的位置。

例如,在這個框中,在“... like this”之后有一個新行,一個在“... where it”之后,兩個在“...之后插入”。

所以,問題實際上是如何在HTML5畫布中進行自動換行

這一切都是為了將​​包含文本和/或照片的一些標准HTML元素轉換為HTML5畫布。 不幸的是,'.fillText()'方法不夠智能,不能為我打破一段文字,所以我需要“手動”檢測每一行。

你可能會做的是measureText然后一次添加一個單詞。 測量第一個單詞,如果它適合容器的寬度( ctx2d.measureText(words).width <= containerWidth ),則可以添加另一個單詞並再次測量。 直到字符串不適合。 如果沒有 - 你必須在下一行fillText

至於手動插入的換行符,它們在HTML中具體表示,可以是textareas中的\\n\\r \\n字符,也可以是HTML元素,如<br \\> 因此,在測量文本之前,您可能希望按段落拆分它。

在textareas:

var paragraphs = textarea.value.split('\n');

在非形式元素中:

var paragraphs = [];

// getting all <p> and elements in a typical HTML element
// as well as individual text nodes (they are just DOM-nodes),
// separated by <br /> elements
var innerNodes = nonFormElement.childNodes;

for (var i = 0, len = innerNodes.length; i += 1) {
    // if a sub-element has some text in it,
    // add the text to our list
    var content = innerNodes[i].textContent;
    if (content) {
        paragraphs.push(content);
    }
}

我不確定你想要實現的目標。 但是這里有一個簡單的技巧可以用來識別單個單詞的位置。 看到這個小提琴


var $text = $('#text'),
    breaks = [],
    top;

// wrap words (\w+) and punctuation (\S+) [well, non-word and non-space]
// in <spans> we can easily identify
$text.html($text.text().replace(/(\w+|\S+)/g, '<span>$1</span>'));

$text.children().each(function() {
    var $this = $(this),
        _top = $this.position().top;

    if (top === undefined) {
        top = _top;
    } else if (top < _top) {
        top = _top;
        // moved a row down
        breaks.push($this.prev());
        $this.prev().css('color', 'red');
    }
});


console.log(breaks);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM