选择并动态设置长HTML段落的有效方式

时间:2015-08-27 16:56:18

标签: javascript html css

我正在构建一个文本阅读器,它可以呈现很长的文本段落,并且都需要记录单个单词的点击次数,并且还要动态地为单个单词着色。但是,它不需要是可编辑的。

构建此类html的最有效方法(适用于现代,移动和浏览器html引擎)是什么?我们之前所拥有的是每个单词和空间都是自己的跨度,并且附有听众的东西。这对我来说似乎效率低下。

1 个答案:

答案 0 :(得分:1)

https://stackoverflow.com/a/9304990/441757的答案可能会提供一些见解。

http://jsfiddle.net/Vap7C/80/

上有一个演示
$("body").click(function() {
    // Gets clicked on word (or selected text if text is selected)
    var t = '';
    if (window.getSelection && (sel = window.getSelection()).modify) {
        // Webkit, Gecko
        var s = window.getSelection();
        if (s.isCollapsed) {
            s.modify('move', 'forward', 'character');
            s.modify('move', 'backward', 'word');
            s.modify('extend', 'forward', 'word');
            t = s.toString();
            s.modify('move', 'forward', 'character'); //clear selection
        }
        else {
            t = s.toString();
        }
    } else if ((sel = document.selection) && sel.type != "Control") {
        // IE 4+
        var textRange = sel.createRange();
        if (!textRange.text) {
            textRange.expand("word");
        }
        // Remove trailing spaces
        while (/\s$/.test(textRange.text)) {
            textRange.moveEnd("character", -1);
        }
        t = textRange.text;
    }
    alert(t);
});