像“Ctrl+A"一样选择文本单击文本时?

2022-01-24 00:00:00 range javascript html

当我单击或双击 <p> 标记时,我想选择段落中的文本.不高亮,就像用鼠标做一个选择区域来选择要选择的文本!

I want to select the text in a paragraph when I click or double click the <p> tag. Not highlight, just like using mouse to make a select area to choose text to be selected!

我在页面上有几个段落和*.rar文件的链接地址,当我点击其中一个时,我想选择所有的文本.我认为文本框可以这样工作,但我喜欢它在段落或链接标签中.

I have several paragraph and *.rar file link addresses on the page, and I want to select all the text when I click on one of them. I think the textbox could work that way but I like it to be in a paragraph or link tag.

有没有办法通过单击另一个元素来选择段落中的所有文本?

Is there a way to select all text in paragraph by clicking another element?

推荐答案

这是一个函数,它将选择你传递给它的元素的内容:

Here's a function that will select the contents of the element you pass to it:

function selectElementContents(el) {
    var range;
    if (window.getSelection && document.createRange) {
        range = document.createRange();
        var sel = window.getSelection();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.body && document.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
}

window.onload = function() {
    var el = document.getElementById("your_para_id");
    selectElementContents(el);
};

相关文章