2016-01-21 74 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

相關問題