简体   繁体   English

contenteditable .execCommand()没有解雇?

[英]contenteditable .execCommand() not firing?

Im experimenting on a custom WYSIWYG editor using contenteditable. 我正在尝试使用contenteditable自定义WYSIWYG编辑器。 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. 我的问题是,当我点击图像(B)时文本只是粗体,而不是当我点击周围的蓝色区域时....但警报确实如此。 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. 这是一个小提琴http://jsfiddle.net/3b4QM/我将图像更改为B,因为路径被破坏了。

console.log(this) 

returns 回报

<li class="wysiwyg-b" original-title="Bold">

I faced the same problem when I built up Froala Editor ( https://froala.com/wysiwyg-editor ). 我在构建Froala编辑器时遇到了同样的问题( 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. <li>放置一个按钮可以解决问题。 Just make sure the button fits the entire <li> . 只需确保按钮适合整个<li>

See http://jsfiddle.net/xdCjD/2/ http://jsfiddle.net/xdCjD/2/

In HTML: 在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 在CSS中,从li中删除填充并将其设置为按钮

#apt-wysiwyg li button {
    padding: 5px;
    height: 30px;
    width: 30px; 
    background: transparent;
    border:none;
}

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. 虽然您正在使用img注册该事件,但它可能没有帮助。 Worth a shot anyway 无论如何值得一试

What happens is that your editable text gets deselected when you click the li element. 当您单击li元素时,会取消选择您的可编辑文本。 I think binding the event to mousedown will solve your problem: 我认为将事件绑定到mousedown将解决您的问题:

 $(".wysiwyg-b").on('mousedown',function() {
        var test=document.execCommand('bold',false,true);
        alert(test);        
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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