javascript从网页中选择文本
我正在尝试编写一个书签,它可以抓取网页上的任何选定文本并将其发送到我的网站。它应该(希望)能够在 Chrome、FFX、Safari 和 IE 中运行。我进行了搜索并找到了一个功能,但它似乎不起作用。这是代码:
<html>
<body>
<div onClick=getSelText()>Click</div>
<div>please select me</div>
</body>
<script language=javascript>
function getSelText(){
var txt = 'nothing';
if (window.getSelection){
txt = "1" + window.getSelection();
} else if (document.getSelection) {
txt = "2" + document.getSelection();
} else if (document.selection) {
txt = "3" + document.selection.createRange().text;
} else return;
alert("selected text = " + txt);
}
</script>
</html>
当我选择 div 中的文本“请选择我”并点击单击 div 时,我只得到“所选文本 = 1”,
谢谢
I'm trying to write a bookmarklet that grabs any selected text on a web page and sends it to my website. It should (hopefully) work in Chrome, FFX, Safari, and IE. I did a search and found a function, but it doesn't appear to work. Here is the code:
<html>
<body>
<div onClick=getSelText()>Click</div>
<div>please select me</div>
</body>
<script language=javascript>
function getSelText(){
var txt = 'nothing';
if (window.getSelection){
txt = "1" + window.getSelection();
} else if (document.getSelection) {
txt = "2" + document.getSelection();
} else if (document.selection) {
txt = "3" + document.selection.createRange().text;
} else return;
alert("selected text = " + txt);
}
</script>
</html>
when I select the text in the div "please select me" and hit the click div, I just get "selected text = 1"
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您单击 div 时,您取消选择文本,因此选择为 ''。如果您选择“单击”文本的一部分,它应该可以工作。或者,如果您选择某些内容并在地址栏中输入“javascript: getSelText()”。
When you click the div, you deselect the text, so selection is ''. If you select part of "Click" text it should work. Or if you select something and type "javascript: getSelText()" in the address bar.