我正在寻找一种方法来在 Chrome 中选择网站上的文本,并根据文本选择弹出覆盖/工具提示内容。
有没有人以前做过这个或者从他们的头脑中知道如何弹出工具栏?
非常感谢。
最佳答案
您需要做的就是监听鼠标事件:
- mousedown:隐藏气泡。
- mouseup:显示气泡。
例如,这可能会帮助您入门。需要进行更多调整,以确定您是否从下->上、右->左等(所有方向)开始选择。您可以使用以下代码作为启动:
contentscript.js
// Add bubble to the top of the page.
var bubbleDOM = document.createElement('div');
bubbleDOM.setAttribute('class', 'selection_bubble');
document.body.appendChild(bubbleDOM);
// Lets listen to mouseup DOM events.
document.addEventListener('mouseup', function (e) {
var selection = window.getSelection().toString();
if (selection.length > 0) {
renderBubble(e.clientX, e.clientY, selection);
}
}, false);
// Close the bubble when we click on the screen.
document.addEventListener('mousedown', function (e) {
bubbleDOM.style.visibility = 'hidden';
}, false);
// Move that bubble to the appropriate location.
function renderBubble(mouseX, mouseY, selection) {
bubbleDOM.innerHTML = selection;
bubbleDOM.style.top = mouseY + 'px';
bubbleDOM.style.left = mouseX + 'px';
bubbleDOM.style.visibility = 'visible';
}
contentscript.css
.selection_bubble {
visibility: hidden;
position: absolute;
top: 0;
left: 0;
background:-webkit-gradient(linear, left top, left bottom, from(#2e88c4), to(#075698));
}
list .json
将匹配部分更改为您要注入(inject)这些内容脚本的域。
...
...
"content_scripts": [
{
"matches": ["http://*/*"],
"css": ["main.css"],
"js": ["main.js"],
"run_at": "document_end",
"all_frames": true
}
...
...
如果你想让它看起来像一个泡泡,Nicolas Gallagher 做了一些很棒的 CSS3 demos为了泡泡!
关于javascript - 文本选择和气泡覆盖作为 Chrome 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4409378/