[英]Wrap an html tag after clicking a toolbar button using js or jquery
I want to do something similar to what this website and wordpress does. 我想做类似于这个网站和wordpress的做法。 When a user highlights text on the screen, then clicks a button on the toolbar it will wrap an html tag around the text. 当用户在屏幕上突出显示文本时,然后单击工具栏上的按钮,它将在文本周围包裹html标记。 In jquery I would probably use the .wrap class but how would I detect if the user highlighted something. 在jquery中我可能会使用.wrap类,但是我如何检测用户是否突出显示了某些内容。
For example, when the user writes Hello World
then clicks on the bold button it will say <b>Hello World</b>
例如,当用户编写Hello World
时,单击粗体按钮,它将显示<b>Hello World</b>
Get the text of the html element which is wrapping the text, then add as html the text embedded in the <b>
tag. 获取包装文本的html元素的文本,然后将嵌入在<b>
标记中的文本添加为html。
See jQuery DOM Manipulation for tutorials. 有关教程,请参阅jQuery DOM Manipulation 。
This mainly requires (1) accessing the selectionStart
and selectionEnd
properties of the input / textarea element and (2) replacing the substring of the value
property across that range with the same text, but wrapped in the desired start and end tags. 这主要要求(1)访问input / textarea元素的selectionStart
和selectionEnd
属性,以及(2)用相同的文本替换该范围内的value
属性的子字符串,但包含在所需的开始和结束标记中。 Also, I think it makes sense to reselect the replaced text, which requires a couple of calls to select()
and setSelectionRange()
. 另外,我认为重新选择被替换的文本是有意义的,这需要对select()
和setSelectionRange()
进行几次调用。 Also, if there's no selection (meaning start equals end) it's probably a good idea to do nothing at all. 此外,如果没有选择(意味着开始等于结束),那么根本不做任何事情可能是个好主意。
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>
I used this question to get the selected text. 我用这个问题来获取所选文本。 And this question to get the element with selected text in it. 这个问题是为了获得带有选定文本的元素。 I combined them in a single function. 我将它们组合在一个功能中。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.