在网页上的文本选择上创建悬停按钮

时间:2016-04-21 07:07:23

标签: javascript jquery

我想在网页上的突出显示/选定文本附近创建一个悬停类型按钮。 像这样的东西。一旦有人选择了某些文本,该按钮就会出现,而当没有选择文本时,该按钮就会消失。按钮应位于选择的末尾。

enter image description here

我对网络开发比较陌生。我知道一点JavaScript和HTML。请指导我完成这个。我应该怎么开始?

2 个答案:

答案 0 :(得分:2)

尝试使用window.getSelection(),在此处查看http://jsfiddle.net/2C6fB/390/

答案 1 :(得分:1)

您可以从捕获mouseup事件开始获取所选文本,并创建一个隐藏div来显示您的选项,这些选项仅在用户选择文本时显示。我创建了一个jsfiddle来帮助你开始:https://jsfiddle.net/zaffer/rmjn7rkx/

负责显示选项的div:

<div id="option" class="arrow_box">
    <div id="copy">
      Copy
    </div>
    <div id="separator"> | </div>
    <div id="speak">
      Speak
    </div>
</div>

负责捕获选择事件和显示选项框的脚本:

$(document).ready(function() {
  var mouseX;
  var mouseY;

  $(document).mousemove(function(e) {
    mouseX = e.pageX;
    mouseX -= 45;
    mouseY = e.pageY;
    mouseY -= 40;
    var selection = "";

    if (window.getSelection) {
      selection = window.getSelection();
    } else if (document.selection) {
      selection = document.selection.createRange();
    }
    if (selection == "") {
      $("#option").fadeOut();
    }
  });

  function calculatePositionAndDisplay() {
    $('#option').css({
      'top': mouseY,
      'left': mouseX
    }).fadeIn('slow');
  }

  $(document.body).bind('mouseup', function(e) {
    var selection = "";

    if (window.getSelection) {
      selection = window.getSelection();
    } else if (document.selection) {
      selection = document.selection.createRange();
    }

    if (selection.toString() !== '') {
      calculatePositionAndDisplay();
    }
  });

  $(document).on("click", "#copy", function() {
    // Copy to clipboard code here
  });
  $(document).on("click", "#speak", function() {
    // Speak code here
  });
});

用于创建选项框的CSS:

#option {
  display: none;
  background: #636363;
  /* For browsers that do not support gradients */
  background: -webkit-linear-gradient(#8d8d8d, #0d0d0d);
  /* For Safari 5.1 to 6.0 */
  background: -o-linear-gradient(#8d8d8d, #0d0d0d);
  /* For Opera 11.1 to 12.0 */
  background: -moz-linear-gradient(#8d8d8d, #0d0d0d);
  /* For Firefox 3.6 to 15 */
  background: linear-gradient(#8d8d8d, #0d0d0d);
  /* Standard syntax */
  color: #fff;
  position: absolute;
  border-radius: 5px;
  z-index: 20px;
}

#copy {
  width: 45px;
  float: left;
  text-align: center;
  padding-top: 3px;
  padding-left: 3px;
}

#separator {
  width: 1px;
  padding: 3px;
  float: left;
}

#speak {
  width: 50px;
  text-align: center;
  padding-top: 3px;
  float: left;
  padding-right: 3px;
}

.arrow_box {
  position: relative;
  background: #0d0d0d;
}

.arrow_box:after {
  top: 100%;
  left: 50%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
  border-color: rgba(99, 99, 99, 0);
  border-top-color: #0d0d0d;
  border-width: 5px;
  margin-left: -5px;
}