问题
Im experimenting on a custom WYSIWYG editor using contenteditable. I'm using the following code to make the selected text bold:
$('.wysiwyg-b').click(function() {
document.execCommand('bold',false,true);
alert('hi');
});
<li class="wysiwyg-b" title="Bold"><img src="images/icons/black/png/font_bold_icon&16.png"> </li>
And it looks like this:

My problem is, the text is only made bold when I click on the image(B), not when I click on the blue surrounding area....but the alert does. What could be causing this issue?
Here is a fiddle http://jsfiddle.net/3b4QM/ I changed the image to a B because the path was broken.
console.log(this)
returns
<li class="wysiwyg-b" original-title="Bold">
回答1:
I faced the same problem when I built up Froala Editor (https://froala.com/wysiwyg-editor). It happens because you loose the selection when you click the surroundings. Placing a button inside the <li>
will solve the problem. Just make sure the button fits the entire <li>
.
See http://jsfiddle.net/xdCjD/2/
In HTML:
<div id="apt-wysiwyg">
<ul>
<li class="wysiwyg-b" title="Bold"><button><img src="images/icons/black/png/font_bold_icon&16.png"></button></li>
</ul>
</div>
In CSS, remove the padding from li and set it to the button
#apt-wysiwyg li button {
padding: 5px;
height: 30px;
width: 30px;
background: transparent;
border:none;
}
回答2:
Quick suggestion if you're writing it into the page after the page has loaded try:
$('.wysiwyg-b').on('click', function() {
document.execCommand('bold',false,true);
alert('hi');
});
Although you are getting the img to register the event so it might not help. Worth a shot anyway
回答3:
What happens is that your editable text gets deselected when you click the li
element. I think binding the event to mousedown will solve your problem:
$(".wysiwyg-b").on('mousedown',function() {
var test=document.execCommand('bold',false,true);
alert(test);
});
来源:https://stackoverflow.com/questions/21546993/contenteditable-execcommand-not-firing