文本选择和气泡覆盖为Chrome扩展程序

bai*_*aik 12 javascript google-chrome google-chrome-extension jquery-tooltip

我正在寻找一种在Chrome网站上选择文字的方法,并根据文字选择提供包含内容的叠加/工具提示.

有没有人以前做过这个或者从头顶知道如何制作工具包弹出窗口?

非常感激.

Moh*_*our 28

您需要做的就是监听鼠标事件:

  • mousedown:隐藏泡沫.
  • mouseup:显示气泡.

例如,这可能有助于您入门.需要进行更多调整,以确定是否从down-> up,right-> left等(所有方向)启动了选择.您可以使用以下代码作为启动:

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';
}
Run Code Online (Sandbox Code Playgroud)

contentscript.css

.selection_bubble {
  visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
  background:-webkit-gradient(linear, left top, left bottom, from(#2e88c4), to(#075698));
}
Run Code Online (Sandbox Code Playgroud)

的manifest.json

将匹配部分更改为要注入这些内容脚本的域.

...
...
  "content_scripts": [
    {
      "matches": ["http://*/*"],
      "css": ["main.css"],
      "js": ["main.js"],
      "run_at": "document_end",
      "all_frames": true
    }
...
...
Run Code Online (Sandbox Code Playgroud)

如果你想让它看起来像一个泡泡,Nicolas Gallagher 为泡泡做了一些很棒的CSS3 演示!

  • 您的Chrome扩展程序答案非常棒,并且投放的太少.一旦我可以分配赏金(24小时后),你就可以得到所有.非常感谢! (2认同)