简体   繁体   中英

Text select (ready to use clipboard operations)

http://cdnjs.com/libraries/twitter-bootstrap/

in this website when i mouseover the links given the text is selected(like the mouse text select and not css styling).

i tried to check what's changing in inspect element i found none.

i tried to find out if js or jquery has methods to do this. i found .select() method of jquery but its usable only on form elements and there is no deselect() method in jquery so its definetely no that.

so whats under the hood?

UPDATE:

i found this solution i tried it in jsfiddle it works perfect. but its written in js with dom node manupulations and it just looks like greek and latin to me. i am not able to write the jquery version of this algorithm.

HTML:

<p id="selectable">hello</p>

JS:

function fnSelect(objId) {
    fnDeSelect();
    if (document.selection) {
    var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(objId));
    range.select();
    }
    else if (window.getSelection) {
    var range = document.createRange();
    range.selectNode(document.getElementById(objId));
    window.getSelection().addRange(range);
    }
}

function fnDeSelect() {
    if (document.selection) document.selection.empty(); 
    else if (window.getSelection)
            window.getSelection().removeAllRanges();
}

$(document).ready(function(){
    $("p").on("mouseover",function(){
        var id = $(this).attr("id");
        fnSelect(id);
    });    
    $("p").on("mouseout",function(){
        fnDeSelect();
   });
});

Finding this was way more trouble than it should have been. Here's exactly what you can use:

From MDN:

window.getSelection().selectAllChildren(elementObject);

Extended studies found here (MDN again)

If it were me, I would do this to achieve the effect:

function onMouseOver(e) {
    window.getSelection().selectAllChildren(e.currentTarget);
}
function onMouseOut(e) {
    window.getSelection().removeAllRanges(e.currentTarget);
}
document.getElementById("top").addEventListener("mouseenter", onMouseOver, false);
document.getElementById("top").addEventListener("mouseleave", onMouseOut, false);

Live Demo :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM