繁体   English   中英

select 点击时 span 内的文本

[英]select text inside span on click

我想获取我点击的文本,所以如果我点击“mother”这个词,日志只会显示这个词“mother”,即使它与另一个词在一个范围内,

我使用了这段代码,但它甚至没有 select 跨度:

 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>

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>

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM