简体   繁体   中英

Javascript “getSelection” only if it's in a certain div

So I'm trying to collect what people are selecting on our site. Currently, it works EVERYWHERE, and I don't want that. I only want it if they are selecting in a certain DIV.

it's basically a simple modification to a script I found.

<script type="text/javascript">
function appendCopyright() {
    var theBody = document.getElementsByClassName("sbReview")[0];
    var selection;
    selection = window.getSelection();
    var copyrightLink = '<br /><br /> - Read more at: <a href="'+document.location.href+'">'+document.location.href+'</a><br />&copy;2012 <? printf($product. ' & ' .$spOrganization); ?>';
    var copytext = selection + copyrightLink;
    var extra = document.createElement("div");
    extra.style.position="absolute";
    extra.style.left="-99999px";
    theBody.appendChild(extra);
    extra.innerHTML = copytext;
    selection.selectAllChildren(extra);
    window.setTimeout(function() {
    theBody.removeChild(extra);
    },0);
}
document.oncopy = appendCopyright;

I tried modifying selection = window.getSelection(); but it just broke it :(

Basically, I want the above code, ONLY to work in a certain div, not the whole body

可能您不应该使用document.oncopy ,而是尝试使用div.oncopy ,其中div是您感兴趣的div元素。

var selection = getSelection().toString(); is your solution - getSelection() returns a Selection object and you can get the string just by using .toString() method. More properties and methods of Selection object could be found here: https://developer.mozilla.org/en-US/docs/DOM/Selection

According to the Mozilla JS docs the selection class has a method containsNode . The following should work.

function appendCopyright() {
    var theBody = document.getElementsByClassName("sbReview")[0];
    var selection;
    selection = window.getSelection();
    // HERE's THE GOODS
    // set aPartlyContained to true if you want to display this
    // if any of your node is selected
    if(selection.containsNode(aNode, aPartlyContained)){
        var copyrightLink = '<br /><br /> - Read more at: <a href="'+document.location.href+'">'+document.location.href+'</a><br />&copy;2012 <? printf($product. ' & ' .$spOrganization); ?>';
        var copytext = selection + copyrightLink;
        var extra = document.createElement("div");
        extra.style.position="absolute";
        extra.style.left="-99999px";
        theBody.appendChild(extra);
        extra.innerHTML = copytext;
        selection.selectAllChildren(extra);
        window.setTimeout(function() {
            theBody.removeChild(extra);
        },0);
    }
}
document.oncopy = appendCopyright;

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