简体   繁体   中英

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. When a user highlights text on the screen, then clicks a button on the toolbar it will wrap an html tag around the text. In jquery I would probably use the .wrap class but how would I detect if the user highlighted something.

For example, when the user writes Hello World then clicks on the bold button it will say <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.

See jQuery DOM Manipulation for tutorials.

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. Also, I think it makes sense to reselect the replaced text, which requires a couple of calls to select() and 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM