我想做一些類似於本網站和wordpress的功能。當用戶在屏幕上突出顯示文本時,然後單擊工具欄上的按鈕,它會在文本週圍包裹一個html標籤。在jQuery中,我可能會使用.wrap類,但是如何檢測用戶是否突出顯示了某些內容。使用js或jquery點擊工具欄按鈕後包裝html標籤
例如,當用戶寫Hello World
然後點擊大膽的按鈕,它會說<b>Hello World</b>
我想做一些類似於本網站和wordpress的功能。當用戶在屏幕上突出顯示文本時,然後單擊工具欄上的按鈕,它會在文本週圍包裹一個html標籤。在jQuery中,我可能會使用.wrap類,但是如何檢測用戶是否突出顯示了某些內容。使用js或jquery點擊工具欄按鈕後包裝html標籤
例如,當用戶寫Hello World
然後點擊大膽的按鈕,它會說<b>Hello World</b>
這主要要求(1)訪問input/textarea元件和(2)具有相同的文本替換整個該範圍內的value
屬性的子串的selectionStart
和selectionEnd
性能,但包裹在期望的開始和結束標記。另外,我認爲重新選擇替換的文本是有意義的,這需要對select()
和setSelectionRange()
進行幾次調用。另外,如果沒有選擇(意味着開始等於結束),那麼根本就不應該做任何事情。
window.selWrapBold = function(id) { selWrap(id,'<b>','</b>'); };
window.selWrapItalic = function(id) { selWrap(id,'<i>','</i>'); };
window.selWrap = function(id,startTag,endTag) {
let elem = document.getElementById(id);
let start = elem.selectionStart;
let end = elem.selectionEnd;
let sel = elem.value.substring(start,end);
if (sel==='') return;
let replace = startTag+sel+endTag;
elem.value = elem.value.substring(0,start)+replace+elem.value.substring(end);
elem.select();
elem.setSelectionRange(start,start+replace.length);
} // end selWrap()
<input type="button" value="bold" onclick="selWrapBold('ta1');"/>
<input type="button" value="italic" onclick="selWrapItalic('ta1');"/>
<br/>
<textarea id="ta1"></textarea>
獲取html元素中的哪一個包裹中的文本,然後添加爲HTML嵌入<b>
標籤文本。
查看jQuery DOM Manipulation的教程。
我以前this問題得到選定的文本。並this問題到 獲取其中的選定文本的元素。我將它們組合在一個函數中。
function updateHighlightedText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
var node = $(window.getSelection().anchorNode.parentNode); //Get the selected node
node.html(node.text().replace(text, "<b>"+text+"</b>")); //Update the node
}
這可能幫助: http://stackoverflow.com/questions/5001608/how-to-know-if-the-text-in-a-textbox-is-selected –