0
在我的web應用程序中,我試圖爲文本元素的click和mouseup事件實現不同的行爲。在mouseup事件中,我檢查是否存在選定的文本並對其執行操作。在點擊事件時,我會做其他事情,比如在點擊文本的地方導航。但是,如果有選定的文本,我不會在點擊事件中執行代碼,這是我卡住的部分。這裏是什麼,我現在在做一個模式:確定dom元素是否包含突出顯示的文本
//the function that returns selected text as string
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
function onMouseUp(event) {
var selection = getSelectionText();
if (selection != "") {
alert("Selected text: " + selection);
}
}
function onClick(event) {
alert("You clicked the text.");
}
<body>
<h2 onclick="onClick(); return false;" onmouseup="onMouseUp(); return false;">
text to click or select
</h2>
</body>
我想要做這樣的事情在onclick處理程序
function onClick(event)
{
if (!hasSelectedParts(this)) // want to implement hasSelectedParts() function
{
alert("You clicked the text.");
}
}
我如何可以實現hasSelectedParts(一個DOMElement )功能?也就是說, 是否有一種檢測dom元素是否具有某些選定部分的簡單方法。
'window.getSelection()。anchorNode'?可能需要爬過/爬過,但這是條目 – dandavis
Seconding @dandavis - 查看一些關於[window.getSelection]的文檔(https://developer.mozilla.org/en-US/docs/Web/API/窗口/ getSelection)。 –