[英]Get Selected Text In ContentEditable DIV?
所以我在我的Rails應用程序中有一個可信的div,並且需要能夠在突出顯示時在文本上方顯示一個小彈出窗口。 目前我的代碼有效,並在警報中顯示突出顯示的文本。 但是,該函數在mouseup上執行,因此當您單擊div開始鍵入或突出顯示時,它會拋出一個空警報。
這是我的代碼:
function getSelected() {
if (window.getSelection) {
return window.getSelection();
}
else if (document.getSelection) {
return document.getSelection();
}
else {
var selection = document.selection && document.selection.createRange();
if (selection.text) {
return selection.text;
}
return false;
}
return false;
};
$("#content-create-partial").bind("mouseup", function(){
var text = getSelected();
if(text) {
console.log(text);
}
else{
console.log("Nothing selected?");
};
});
當用戶點擊contentEditable div時,如何防止jQuery執行該函數? 我只希望它在突出顯示實際文本時執行。
您可以比較window.getSelection().anchorOffset
和window.getSelection().extentOffset
以查看它們是否相等。 如果是,則只是正常點擊。
如果未選擇任何內容,則以下內容將返回true。
靈感來自@Tarun Dugar。 但是並不適用於所有瀏覽器。 以下工作。
window.getSelection().focusOffset == window.getSelection().anchorOffset;
您可以簡單地檢查Selection.toString()
方法是否返回空字符串
if(window.getSelection().toString()){
// do something
}
試試這個
window.getSelection().anchorNode.data.substring( window.getSelection().anchorOffset,window.getSelection().extentOffset )
嘗試在這里工作。
當用戶開始選擇時會激活“selectstart”事件。 沒有選擇結束事件,但您可以在“selectstart”事件觸發后監聽mouseup事件,以確保選擇已發生。
編輯:
檢查 - HTML內容可編輯div:選擇文本事件
只需檢查選擇是否為空: if ($.trim( text) != '') ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.