所以我正在尝试收集人们在我们网站上选择的内容。目前,它无处不在,我不希望如此。如果他们在某个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 />©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
答案 0 :(得分:4)
可能您不应该使用document.oncopy
,而是尝试使用div.oncopy
,其中div
是您感兴趣的div元素。
答案 1 :(得分:0)
var selection = getSelection().toString();
是您的解决方案 - getSelection()
返回一个Selection对象,您只需使用.toString()
方法即可获取该字符串。可以在此处找到Selection对象的更多属性和方法:https://developer.mozilla.org/en-US/docs/DOM/Selection
答案 2 :(得分:0)
根据Mozilla JS docs,选择类有一个方法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 />©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;