【问题标题】:Wrap an html tag after clicking a toolbar button using js or jquery使用 js 或 jquery 单击工具栏按钮后包装 html 标记
【发布时间】:2023-03-18 12:53:01
【问题描述】:
我想做一些类似于这个网站和 wordpress 所做的事情。当用户在屏幕上突出显示文本,然后单击工具栏上的按钮时,它将在文本周围包裹一个 html 标记。在 jquery 中,我可能会使用 .wrap 类,但我将如何检测用户是否突出显示了某些内容。
例如,当用户写Hello World然后点击粗体按钮时,它会说<b>Hello World</b>
【问题讨论】:
标签:
javascript
jquery
html
css
【解决方案1】:
这主要需要 (1) 访问 input/textarea 元素的 selectionStart 和 selectionEnd 属性,以及 (2) 用相同的文本替换该范围内的 value 属性的子字符串,但包裹在所需的开始和结束标签中。另外,我认为重新选择替换的文本是有意义的,这需要对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>
【解决方案3】:
我使用this question 来获取选定的文本。和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
}