我正在寻找一种方法,将我选中的文字周围的框架/边框(如Evernote Web Clipper:下图)添加到我的Chrome扩展程序中。
为此,我想捕获选择的HTML代码并在当前所选文本周围添加框架/边框。但我不明白我该怎么做......
这是我的代码:
的manifest.json:
{
"name": "Selected Text",
"version": "0.1",
"description": "Selected Text",
"manifest_version": 2,
"browser_action": {
"default_title": "Selected Text",
"default_icon": "online.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["popup.js"]
}
]
}
popup.js:
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
console.log(selection[0]);
if(selection[0].length > 0){
document.getElementById("text").value = selection[0];
}
});
popup.html:
<!DOCTYPE html>
<html>
<head>
<script src="popup.js"></script>
<style>
body { width: 300px; }
textarea { width: 250px; height: 100px;}
</style>
</head>
<body>
<textarea id="text"> </textarea>
</body>
</html>
答案 0 :(得分:2)
您可以使用mouseup
这样的事件来执行此操作:
// Add event listener for mouseup (there is no event for selection)
document.addEventListener('mouseup', highlightSelectedBlock, false)
function highlightSelectedBlock () {
// TODO Filter only selections
// Get Node where selection starts
let elementWhereSelectionStart = window.getSelection().anchorNode
// TODO Get Node where selection ends with Selection.focusNode()
// TODO Get Nodes in between start and end of selection
// I've hardcoded finding closest block element for a simplicity
let closestBlockElement = elementWhereSelectionStart.parentNode
// Add non disturbing border to selected elements
// For simplicity I've adding outline only for the start element
closestBlockElement.style.outline = '1px solid blue'
// TODO Clear outline on some event: saving selection, ending selection etc
setTimeout(() => { closestBlockElement.style.outline = 'none' }, 2000)
}
&#13;
<p>First line
<p>Second line
<p>Third line
&#13;
但对于现实生活来说,应该更加复杂,想一想:
使用window.requestAnimationFrame()不断为选择对象推送DOM而不是向mouseup
添加事件监听器,这可能是一个好主意。