如何在不包装的情况下创建文本选择工具提示?

时间:2013-08-18 19:04:36

标签: javascript jquery html5 selection textselection

我的最终目标是在文本选择上创建工具提示。然后,用户将能够与类似于this的工具提示进行交互。请注意,我能够通过将选定的文本包装在标签中然后在其上创建工具提示来实现此目的,但由于某些其他要求和功能问题,这不再是我的选择。如果您在元素检查器中的上图中注意到,所选文本未包含在任何类型的标记中,则仅在选择上创建工具提示。我已经查看了this并且它对我不起作用,因为鼠标位置可能与选择结束不同。我需要实际的选择位置。

一般问题:实现这一目标的最佳方法是什么? 更具体的问题:

  • 我应该使用选择的坐标吗?如果是这样,有办法获得矩形选择的顶角的坐标,这样我就可以找到中点并创建一个工具提示。
  • 有没有办法将选择作为一个元素?所以我可以放一个工具提示吗? (注意选择可以是多个节点)

2 个答案:

答案 0 :(得分:13)

假设选择了某些内容

var selection = window.getSelection(),      // get the selection then
    range = selection.getRangeAt(0),        // the range at first selection group
    rect = range.getBoundingClientRect(); // and convert this to useful data

rect现在是 Object ,它保存相对于 Window 的当前滚动坐标的位置。有关此here的更多信息。如果您想要更加精确,可以使用getClientRects返回此类对象的列表,然后您必须将它们放在一起以形成所选区域。

现在,在它周围绘制一个方框(我将使用fixed进行简单的路径以进行演示)

var div = document.createElement('div');   // make box
div.style.border = '2px solid black';      // with outline
div.style.position = 'fixed';              // fixed positioning = easy mode
div.style.top = rect.top + 'px';       // set coordinates
div.style.left = rect.left + 'px';
div.style.height = rect.height + 'px'; // and size
div.style.width = rect.width + 'px';
document.body.appendChild(div);            // finally append

您可能需要考虑滚动位置,以便使用绝对定位。如果没有其他可滚动元素,这意味着您只需要考虑window.scrollXwindow.scrollY的值,这些是窗口 x 的位置y 在访问它们时以像素为单位的坐标。

var div = null;

function drawBorderAroundSelection() {
  var selection = window.getSelection(), // get the selection then
    range = selection.getRangeAt(0), // the range at first selection group
    rect = range.getBoundingClientRect(); // and convert this to useful data

  if (rect.width > 0) {
    if (div) {
      div.parentNode.removeChild(div);
    }
    div = document.createElement('div'); // make box
    div.class = 'rect';
    div.style.border = '2px solid black'; // with outline
    div.style.position = 'fixed'; // fixed positioning = easy mode
    div.style.top = rect.top + 'px'; // set coordinates
    div.style.left = rect.left + 'px';
    div.style.height = rect.height + 'px'; // and size
    div.style.width = rect.width + 'px';
    document.body.appendChild(div); // finally append
  }
}

window.onmouseup = drawBorderAroundSelection;
<p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut dolor porta neque vulputate auctor et a ligula. Quisque bibendum risus magna, eget feugiat erat faucibus sed. Phasellus sed massa elementum, laoreet ipsum non, dignissim orci. Aenean lobortis
  nunc et purus molestie, vel consectetur ligula dapibus. In ut lorem mattis, commodo nisi aliquam, porta ante. Curabitur sit amet libero sed justo finibus porttitor. Donec ac est ultrices, pretium diam sed, blandit nunc. Morbi consequat finibus augue
  vel ultricies. Vestibulum efficitur ante vitae cursus accumsan. Vestibulum rutrum ex ex, a egestas nisi malesuada eu. Pellentesque fermentum, ante id convallis luctus, tellus lectus viverra diam, sit amet convallis ligula lorem sit amet neque.
</p>

答案 1 :(得分:3)

$(document).ready(function () {
  function tweetButtonClick() {
    let selectedText = document.getSelection().toString();
    /*window.open(
      "https://twitter.com/intent/tweet?url=https://www.linkedin.com/in/harsha-vardhan-ch-245197bb/&text=" +
        selectedText
    );*/
    console.log("This is your selected text: ",selectedText);
  }

  const textSelectionTooltipContainer = document.createElement("div");
  textSelectionTooltipContainer.setAttribute(
    "id",
    "textSelectionTooltipContainer"
  );
  textSelectionTooltipContainer.innerHTML = `<button id="textShareTwitterBtn">TWEET</button>`;
  const bodyElement = document.getElementsByTagName("BODY")[0];

  $("body").on("click", "#textShareTwitterBtn", tweetButtonClick);

  bodyElement.addEventListener("mouseup", function (e) {
    var textu = document.getSelection().toString();
    if (!textu.length) {
      textSelectionTooltipContainer.remove();
    }
  });

  document
    .getElementById("textToSelect")
    .addEventListener("mouseup", function (e) {
      let textu = document.getSelection().toString();
      let matchu = /\r|\n/.exec(textu);
      if (textu.length && !matchu) {
        let range = document.getSelection().getRangeAt(0);
        rect = range.getBoundingClientRect();
        scrollPosition = $(window).scrollTop();
        containerTop = scrollPosition + rect.top - 50 + "px";
        containerLeft = rect.left + rect.width / 2 - 50 + "px";
        textSelectionTooltipContainer.style.transform =
          "translate3d(" + containerLeft + "," + containerTop + "," + "0px)";
        bodyElement.appendChild(textSelectionTooltipContainer);
      }
    });
});
#textSelectionTooltipContainer {
  will-change: transform;
  position: absolute;
  width: 100px;
  height: 40px;
  background: #f7d39d;
  top: 0px;
  left: 0px;
  display: flex;
  padding: 5px 10px;
  box-sizing: border-box;
  justify-content: center;
}

#textSelectionTooltipContainer button {
  font-size: 14px;
  border: 1px solid black;
  background: none;
  cursor: pointer;
  margin: 0 2px;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <link rel='stylesheet' href='shareText.css' />
  <title>Text Share Feature</title>
  <script>

  </script>
</head>

<body>
  
  <div id="textToSelect">
  
    <h1>HTML Ipsum Presents</h1>
  
    <p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em>    Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
      sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a> in turpis pulvinar facilisis. Ut felis.</p>
  
    <h2>Header Level 2</h2>
  
    <ol>
      <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
      <li>Aliquam tincidunt mauris eu risus.</li>
    </ol>
  
    <blockquote>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
        elit sit amet quam. Vivamus pretium ornare est.</p>
        <p>
        Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
        </p>
    </blockquote>
  
    <h3>Header Level 3</h3>
  
    <ul>
      <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
      <li>Aliquam tincidunt mauris eu risus.</li>
    </ul>
    <h1>HTML Ipsum Presents</h1>
  
    <p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em>    Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
      sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a> in turpis pulvinar facilisis. Ut felis.</p>
  
    <h2>Header Level 2</h2>
  
    <ol>
      <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
      <li>Aliquam tincidunt mauris eu risus.</li>
    </ol>
  
    <blockquote>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
        elit sit amet quam. Vivamus pretium ornare est.</p>
        <p>
        Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
        </p>
    </blockquote>
  
    <h3>Header Level 3</h3>
  
    <ul>
      <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
      <li>Aliquam tincidunt mauris eu risus.</li>
    </ul>
    <h1>HTML Ipsum Presents</h1>
  
    <p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em>    Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
      sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a> in turpis pulvinar facilisis. Ut felis.</p>
  
    <h2>Header Level 2</h2>
  
    <ol>
      <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
      <li>Aliquam tincidunt mauris eu risus.</li>
    </ol>
  
    <blockquote>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
        elit sit amet quam. Vivamus pretium ornare est.</p>
        <p>
        Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
        </p>
    </blockquote>
  
    <h3>Header Level 3</h3>
  
    <ul>
      <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
      <li>Aliquam tincidunt mauris eu risus.</li>
    </ul>
    <h1>HTML Ipsum Presents</h1>
  
    <p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em>    Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
      sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a> in turpis pulvinar facilisis. Ut felis.</p>
  
    <h2>Header Level 2</h2>
  
    <ol>
      <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
      <li>Aliquam tincidunt mauris eu risus.</li>
    </ol>
  
    <blockquote>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
        elit sit amet quam. Vivamus pretium ornare est.</p>
        <p>
        Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis
        </p>
    </blockquote>
  
    <h3>Header Level 3</h3>
  
    <ul>
      <li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
      <li>Aliquam tincidunt mauris eu risus.</li>
    </ul>
  </div>
  <script src="shareText.js"></script>
</body>
</html>

window.open 可让您打开 Twitter 页面 (https://twitter.com/intent/tweet),您可以在其中共享所选文本和网址。