Select text just like “Ctrl+A” when clicking the t

2019-01-28 03:08发布

问题:

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!

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?

回答1:

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);
};


回答2:

If you are talking about JavaScript, look at Introduction to Range by Peter-Paul Koch (famous for his compatibility tables).



回答3:

You CAN select a whole paragraph with a double click. Why do you want to change that?