Gan*_*kar 4 javascript bookmarklet
我正在构建一个JS书签,它允许我捕获用户在浏览器中选择的文本并将其发送到Web应用程序.我目前检查了几个教程,并有一个如下所示的脚本:
javascript:var t;try {t=((window.getSelection&&window.getSelection())||(document.getSelection&&document.getSelection())||(document.selection&&document.selection.createRange&&document.selection.createRange().text));}catch(e){t="";}alert(t);
Run Code Online (Sandbox Code Playgroud)
为了使它更容易,这里的代码更易读:
javascript:
var t;
try {
t=((window.getSelection&&window.getSelection()) || (document.getSelection&&document.getSelection()) || (document.selection&&document.selection.createRange&&document.selection.createRange().text));
}catch(e)
{
t="";
}
alert(t);
Run Code Online (Sandbox Code Playgroud)
我当前的代码抓取了所选的文本并发出警告,以便我可以看到已捕获的内容.但是,文本的格式对我来说很重要,所以我真正想做的就是在本文中抓取任何HTML.事实上,我认为最好还是找出用户在页面中选择的位置并从所选内容的开头和结尾查找,找到最近的HTML标签,然后抓住其中的内容.(因为用户无法判断他们是否选择HTML或不容易)
我更习惯使用JQuery来做DOM选择,所以现在这有点过头了.(除非你可以使用带有书签的JQuery ......你可以吗?)
谁能帮我这个?(即使只是指着我正确的方向也会很棒,我这样做是为了一个爱好学习项目,所以我很高兴自己想出一些东西.)
Tim*_*own 10
以下函数将返回包含用户选择的HTML的字符串:
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
Run Code Online (Sandbox Code Playgroud)
这是一个书签的缩减版本:
javascript:(function(){var h="",s,g,c,i;if(window.getSelection){s=window.getSelection();if(s.rangeCount){c=document.createElement("div");for(i=0;i<s.rangeCount;++i){c.appendChild(s.getRangeAt(i).cloneContents());}h=c.innerHTML}}else if((s=document.selection)&&s.type=="Text"){h=s.createRange().htmlText;}alert(h);})()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3895 次 |
| 最近记录: |