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

元气小坏坏 提交于 2019-12-12 11:12:30

问题


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?



来源:https://stackoverflow.com/questions/4011490/select-text-just-like-ctrla-when-clicking-the-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!