在JavaScript中,我一眼就知道如何使用window.getSelection()
?
var s = window.getSelection();
s = s.toString().trim();
alert(s);
HTML包含:
<p>This text contains --this; and that-that.</p>
如果单击 - this; ,预期输出应为 this 。 双击应该做得很好,但如何只需单击一下即可完成此操作?
非常感谢所有人,我来到这个解决方案:
$('p').bind('click', function () {
var sel_obj = window.getSelection(); //it will return an object
sel_obj.modify("move","forward","character");
sel_obj.modify("extend","backward","word");
sel_obj.modify("move","backward","character");
sel_obj.modify("extend","forward","word");
var text = sel_obj.toString().trim();
text = text.toLowerCase();
alert (text);
参考文献: https://developer.mozilla.org/en-US/docs/Web/API/Selection
https://developer.mozilla.org/en-US/docs/Web/API/Selection/modify
答案 0 :(得分:0)
您需要通过onclick事件触发您的JavaScript代码。
因此,在你的p元素中,设置onclick到js函数的名称:
<p onClick="myFunction()">Whatever text here</p>
该功能定义为
var myFunction = function(){
var s = window.getSelection();
s = s.toString().trim();
alert(s);
}
答案 1 :(得分:0)
给你一个标识符,然后绑定一个点击功能:
<p>This text contains <span id="this">--this;</span> and that-that.</p>
$( "#this" ).click(function() {
var s = window.getSelection();
s = s.toString().trim();
alert(s);
});
要进行双击,请使用.dblclick
$( "#this" ).dblclick(function() {
var s = window.getSelection();
s = s.toString().trim();
alert(s);
});
答案 2 :(得分:0)
单击时创建零长度选择范围,因此选择的toString()
自然会成为空字符串。
如果您想知道单击发生时存在的整个单词,您将不得不进一步了解getSelection()
返回的内容:https://developer.mozilla.org/en-US/docs/Web/API/Selection
Selection
对象将告诉您DOM树中存在零长度选择的节点,以及您单击该节点的偏移量。您可以轻松获取属于该节点的所有文本 - 但这比您想要的文本更多。
您还需要做的是查看选择偏移处的文本,然后从该点向后和向前扫描以查找字边界。
抱歉,我不知道这种方法不那么复杂 - 据我所知,没有任何东西可以自动为您提供单击选择。
答案 3 :(得分:0)
这是我的实现,demo here
document.addEventListener('mouseup', (e) => {
const selection = window.getSelection();
if (!selection.isCollapsed) {
console.info("[skipping] Selection detected");
return;
}
const word = getWordAt(selection.focusNode.textContent, selection.focusOffset);
if (!word) {
console.info("[skipping] Nothing selected");
return;
}
const range = selection.getRangeAt(0);
const elementOfSelectedWord = range.startContainer.splitText(range.startOffset - word.offset),
elementAfterSelectedWord = elementOfSelectedWord.splitText(word.word.length);
const decoratedElementOfSelectedWord = document.createElement('span');
decoratedElementOfSelectedWord.appendChild(document.createTextNode(elementOfSelectedWord.textContent));
elementOfSelectedWord.parentNode.insertBefore(decoratedElementOfSelectedWord, elementAfterSelectedWord);
elementOfSelectedWord.parentNode.removeChild(elementOfSelectedWord);
const clientRect = decoratedElementOfSelectedWord.getBoundingClientRect();
if (!isMousePosCoveredInClientRect(e, clientRect)) {
console.info("[skipping] Mouse pos is not covered in client rect");
return;
}
drawRedRect(clientRect);
console.log(`${word.word}`);
})
function getWordAt(content, offset) {
const matchLeft = content.substr(0, offset).match(/(\w+)$/);
const left = matchLeft ? matchLeft[1] : "";
const matchRight = content.substr(offset).match(/^(\w+)/);
const right = matchRight ? matchRight[1] : "";
if (!left && !right) {
return null;
}
return {word: left + right, offset: left.length};
}
function isMousePosCoveredInClientRect(event, clientRect) {
return (
event.clientY >= clientRect.y &&
event.clientY <= clientRect.y + clientRect.height &&
event.clientX >= clientRect.x &&
event.clientX <= clientRect.x + clientRect.width
);
}
function drawRedRect(clientRect) { // this is to simulate a popup
const div = document.createElement('div');
Object.assign(div.style, {
display: "block",
position: "absolute",
left: (clientRect.left + window.scrollX) + "px",
top: (clientRect.top + window.scrollY) + "px",
width: clientRect.width + "px",
height: clientRect.height + "px",
border: "1px solid red"
});
document.body.appendChild(div);
setTimeout(() => {
document.body.removeChild(div);
}, 1000)
}