简体   繁体   中英

Toggling H1 and h2 with execCommand

I have a simple text editor and i'd like to toggle h1 tags around the current selection as i do with bold tags. With bold tags i do:

function onBoldClick() {
   document.execCommand( 'bold', false );
}

This automatically toggles b tags around the current selection.

With h1 tags:

function onHeading1Click() {
    document.execCommand('formatBlock', false, '<h1>'); 
}

This only wraps h1 around the selection but there's no way to remove it.
Is there another way to go about this? Nb: it should work on ie

var h1Class = 'your h1 btn class',
    removeH1Class = '.remove-h1';

$(document).on('click', h1Class, function() {
    $(this).removeClass(h1Class).addClass(removeH1Class);
    onHeading1Click();
});

$(document).on('click', removeH1Class, function() {
    $(this).removeClass(removeH1Class).addClass(h1Class);
    onRemoveH1Click();
});

function onHeading1Click() {
    document.execCommand('formatBlock', false, '<h1>'); 
}
function onRemoveH1Click() {
    document.execCommand('formatBlock', false, 'p'); 
}

HTML

 <p><button type="button" id="h1-button">H1</button></p>
 <div id="edit-area" contenteditable="true">
     <h1>This is heading</h1>
     <div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed posuere interdum sem. Quisque ligula eros ullamcorper quis, lacinia quis facilisis sed sapien. Mauris varius diam vitae arcu. Sed arcu lectus auctor vitae, consectetuer et venenatis eget velit. Sed augue orci, lacinia eu tincidunt et eleifend nec lacus. Donec ultricies nisl ut felis, suspendisse potenti.</div>
 </div>

Javascript + jQuery

$('#h1-button').click(function() {
    var html = $('#edit-area').html();
    document.execCommand('formatBlock', false, 'h1');
    if(html == $('#edit-area').html()) {
        document.execCommand('formatBlock', false, 'div');
    }
});

JSFIDDLE DEMO

This is my choice to do this. It's CSS hack and broke semantic, but it's works.

HTML

<p><button type="button" id="h1-button">H1</button></p>
<div contenteditable="true">
    <sup>This is heading</sup>
    <div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed posuere interdum sem. Quisque ligula eros ullamcorper quis, lacinia quis facilisis sed sapien.</div>
</div>

Javascript + jQuery

$('#h1-button').click(function() {
    document.execCommand('superscript', false, null);
});

CSS

sup{
    vertical-align: super;
    display: block;
    font-size: 2em;
    line-height: 1em;
    margin: 20px 0;
    position: relative;
    top: 0;
}

JSFIDDLE DEMO

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