2

所以我试图收集人们在我们网站上选择的内容。目前,它无处不在,我不希望这样。如果他们在某个 DIV 中选择,我只想要它。

它基本上是对我找到的脚本的简单修改。

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

我尝试修改selection = window.getSelection();但它只是破坏了它:(

基本上,我想要上面的代码,只能在某个 div 中工作,而不是整个body

4

3 回答 3

4

可能你不应该使用document.oncopy,而是尝试使用你感兴趣的 div 元素div.oncopydiv

于 2012-10-29T21:56:23.107 回答
0

var selection = getSelection().toString();是您的解决方案 -getSelection()返回一个 Selection 对象,您只需使用.toString()方法即可获取字符串。Selection 对象的更多属性和方法可以在这里找到:https ://developer.mozilla.org/en-US/docs/DOM/Selection

于 2012-10-29T21:51:32.207 回答
0

根据Mozilla JS 文档 ,选择类有一个方法containsNode。以下应该工作。

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;
于 2012-10-29T22:01:48.387 回答