使用javascript在元素中选择一行文本

Select a single line of text within an element with javascript

本文关键字:一行 文本 选择 javascript 元素 使用      更新时间:2023-09-26

我已经找到了很多使用各种形式的onclick="this.select()"来选择元素的全部内容的解决方案,但是否可以使用javascript从元素onclick中选择一行?

例如,我正在编写一本Linux指南,其中涉及<pre><code>标记中的许多bash命令,我不希望用户必须单击并拖动才能逐行选择每个命令,因为这在几十行之后会变得乏味。但是,我也不想将每个命令分离成它自己的元素,这些元素可以用于选择事件。

代码块示例:

<pre><code>
sudo apt-get install foo
cd /etc/bar
sudo cp baz.conf baz.local
sudo nano baz.local
</code></pre>

我希望用户只需单击一行就可以选择它,但没有类或id可供使用。我还希望这适用于页面上的任何<pre><code>块,而不仅仅是特定的块。jQuery解决方案就可以了。

这可能吗?

您可以计算行数,并将其与代码元素的当前垂直鼠标除法器相乘(例如,如果您位于元素中间,则为0.5)。

这是相应的代码片段:

Math.floor(lines.length * (y/height))


基于这个想法的jQuery插件可以这样编码:

jQuery.fn.lineSelection = function(options) {
    var _this = this,
        height = null,
        lines = this.text().split(''n'),
        textChanged = false;
    // remove first empty lines (optional)
    while(lines[0] == '') {
        textChanged = true;
        lines.shift();
    }
    // remove last empty lines
    while(lines[lines.length-1] == '') {
        textChanged = true;
        lines.pop();
    }
    if(textChanged) {
        this.text(lines.join(''n'));
    }
    height = this.height();
    this.on('click', function() {
        var y = event.offsetY,
            // now use the described formula
            lineIndex = Math.floor(lines.length * y/height),
            line = lines[lineIndex];
        _this.trigger('lineClicked', [line, lineIndex]);
    });
    if(options.lineClicked) {
        this.on('lineClicked', options.lineClicked);
    }
};

插件可以这样使用:

$('pre > code').lineSelection({
    lineClicked: function(event, text, index) {
        console.log(text, index);
    }
});


还可以查看正在运行的jsfiddle演示