内容可编辑的div,带有粗体选项 [英] Contenteditable div with bold option
问题描述
我想使用 bold 和 italic 选项使contenteditable div可以在具有相同选项的keyup上的另一个div中显示内容. 我设法显示文本,但没有显示选项.请帮助
I want to make contenteditable div with bold and italic options to display content in another div on keyup with the same options. I managed to display text, but not options. Please help
html:
<button onclick="document.execCommand('bold');">B</button>
<button onclick="document.execCommand('italic');">I</button>
<div id="textarea" contenteditable></div>
<div id="textarea-show"></div>
jquery:
$('#textarea').keyup(function() {
$('#textarea-show').html($(this).text());
});
css:
#textarea { background-color: #fff;
border: 1px solid #ccc;
color: #555;
font-size: 14px;
height: 34px;
width: 450px;
}
#textarea-show{font-size: 2rem;
color:#666;
height:50px;
border: 1px solid #ccc;
width: 450px;
}
示例: https://jsfiddle.net/gqmLtct7/1/
推荐答案
您可以添加两个类别,一个类别为bold
,另一个类别为italic
,对它们进行样式设置并在单击按钮时对其进行切换以激活/停用粗体/斜体(您可以运行下面的代码段,也可以在此处找到更新的jsfiddle ):
You can add two classes, one let's say bold
and the other italic
, style them and toogle them on click of the buttons to activate/deactivate the bold/italic (You can run the code snippet below or you can also find the updated jsfiddle here):
更新
在OP发表评论之后,由于他只想在选定的文本中添加粗体和斜体,因此我对答案做了一些更新.
After the OP's comment, as he wanted to add the bold and italic only to selected text, I've updated my answer a little bit.
更新后的 jsfiddle .
以及更新后的代码:
$('#textarea').keyup(function() {
$('#textarea-show').html($(this).text());
});
$('#bold_btn').on('click', function() {
//$('#textarea, #textarea-show').toggleClass('bold');
document.execCommand('bold');
var text = document.getElementById('textarea').innerHTML;
$('#textarea-show').html(text);
});
$('#italic_btn').on('click', function() {
//$('#textarea, #textarea-show').toggleClass('italic');
document.execCommand('italic');
var text = document.getElementById('textarea').innerHTML;
$('#textarea-show').html(text);
});
#textarea {
background-color: #fff;
border: 1px solid #ccc;
color: #555;
font-size: 14px;
height: 34px;
width: 450px;
}
#textarea-show {
font-size: 2rem;
color: #666;
height: 50px;
border: 1px solid #ccc;
width: 450px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='bold_btn'>B</button>
<button id='italic_btn'>I</button>
<div id="textarea" contenteditable></div>
<div id="textarea-show"></div>
这篇关于内容可编辑的div,带有粗体选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!