2016-01-21 73 views
1

这只是让我困惑。
如下面的代码所示,当您按div中的“ctrl + b”时,字体权重变大,而在textarea中不会发生。
这个问题是根据Marcus Ekwall对Rendering HTML inside textarea的回答的评论。但我不能添加评论,所以我在这里问。 为什么textarea的contenteditable值true不会注册keydown事件

div, textarea { 
 
    width: 100px; 
 
    height: 100px; 
 
    border: 1px solid; 
 
    padding: 5px; 
 
} 
 
textarea { 
 
    resize: none; 
 
} 
 
<div contentEditable="true"></div> 
 
<textarea contentEditable="true" placeholder="textarea"></textarea>

+4

在textarea中'contenteditable'的意思是什么,你仍然不能添加除纯文本以外的东西 – adeneo

+1

在浏览器中按ctrl + b它使用它的默认功能,例如。在Firefox中调用'书签'工具栏。你需要用javascript来捕捉按键事件。 –

+0

您是否阅读过您所指的答案 - > *“这不可能与textarea相媲美”* – adeneo

回答

0

行为是具体的只是浏览器。不同的浏览器有不同的行为。并感谢adeneo的提及:在textarea中,除了纯文本之外,不能添加其他任何内容。

3
在textarea的

不起作用,因为它不支持HTML标签 当它运行document.execCommand(“大胆”)中选择文本添加<b>fdsfsdfds</b>

在这里,您使用的是例子jQuery的(更新)

$("#editor").keypress("c",function(e){ 
 
    
 
\t if(e.ctrlKey) {   
 
     
 
    document.execCommand('bold', false, null); 
 

 

 
    } 
 
    
 
})
#editor { 
 
    width: 200px; 
 
    height: 200px; 
 
    border: 1px solid; 
 
    padding: 5px; 
 
    resize: none; 
 
    border: 1px solid black; 
 
    word-wrap: break-word; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 

 
<div id="editor" contentEditable="true"></div>

请看到这个帖子约按键jquery: keypress, ctrl+c (or some combo like that)

更多的例子约document.execCommand http://codepen.io/netsi1964/pen/QbLLGWhttp://codepen.io/netsi1964/pen/QbLLGW

+0

谢谢你的例子。但是'.blod'会影响文本文件中的所有文本,而不是按'ctrl + b'后的文本。 – jasonxia23

+0

好的,你需要的是实际的文字:**文字**文字 – Osgux

+0

@JasonXia我更新了例子 – Osgux

相关问题