【问题标题】:Why doesn't the document.execCommand work when I click on a div?为什么单击 div 时 document.execCommand 不起作用?
【发布时间】:2012-09-21 06:04:42
【问题描述】:

按钮和 div 都具有相同的“onclick”代码,但 execCommand 似乎只适用于按钮。按下 div 时有什么办法可以让它工作吗?

这是我的小提琴: http://jsfiddle.net/foreyez/ZzL8y/

<button onclick="document.execCommand('bold',false,null);">Bold</button>
<div onclick="document.execCommand('bold',false,null);" style='border:1px solid black;width:50px;'>Bold</div>

<div id='input' contenteditable='true'>
    select some of this text and then hit one of the buttons above
</div>

【问题讨论】:

  • 我猜它不适用于 div,因为您失去了焦点和选择。使用按钮保持焦点。

标签: javascript html


【解决方案1】:

您需要阻止 div 上的 mousedown 事件,因为它会窃取焦点:

Updated fiddle

【讨论】:

  • 出色的康斯坦丁!
【解决方案2】:

看到这个小提琴:- http://jsfiddle.net/ZzL8y/4/
这不是完整的答案,但这些链接可能会对您有所帮助:-

1>set execcommand just for a div

2>select all text in contenteditable div when it focus/click

【讨论】:

    【解决方案3】:

    对于 Firefox,需要在 execCommand 之前设置 contenteditable = true。

    对于 IE 则不需要。

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多