css 单击时选择范围内的文本

4ioopgfo  于 2023-01-10  发布在  其他
关注(0)|答案(2)|浏览(117)

我想得到我点击的文本,所以如果我点击单词"mother"日志只显示这个单词"mother",即使它在一个跨度内与另一个单词,
我使用了以下代码,但它甚至没有选择跨距:

function getSelectedText(e) {

    if(window.getSelection)
        return console.log(window.getSelection().toString());
    else if(document.getSelection)
        return console.log(document.getSelection());
    else if(document.selection)
        return console.log(document.selection.createRange().text);
    return console.log("");
    
}

document.body.onmouseup = getSelectedText;
<div class="destination">
  <span class="word">sister mother</span>
  <span class="word" >brother</span>
  <span class="word" >father</span>
</div>

<h1>hi</h1>
tgabmvqs

tgabmvqs1#

span-split选项可以在所有浏览器中使用,并且不需要使用第三方库。

<body>
        <style>
          .container{
              display: flex;
              gap: 5px;
              flex-wrap: wrap;
          }
      </style>
    <div id="root" class = "container"></div>
    <script>
      var text = 'Soon after this, I started working with Kitty, who has volunteered at the shelter for years, so she knew all the lay of the land and was super helpful.'
      var container = document.getElementById("root")
      text.split(' ').forEach((word)=>{
          var newWord = document.createElement("span")
          newWord.innerText = word
          newWord.className = 'myClass'
          container.appendChild(newWord)
      })
      function handler(event) {
          if (event.target.className === "myClass"){
              console.log(event.target.textContent)
          }
      }
      document.addEventListener('click',handler,false)
    </script>
  </body>
nqwrtyyt

nqwrtyyt2#

function highlight(span) {
  span.classList.toggle("highlight");
  
  
  //select the text and do what ever
  var selectedText = span.innerHTML;
  alert(selectedText);
}
.highlight {
  background-color: lightblue;
}
<span onclick="highlight(this)">sister mother</span>
<span onclick="highlight(this)">brother</span>
<span onclick="highlight(this)">father</span>

相关问题