[英]Twitter Bootstrap button checkboxes toggling issue in making a wysiwyg text editor
I'd like to make a simple text editor to allow people to make the font bold, italicized or underlined. 我想制作一个简单的文本编辑器,允许人们将字体粗体,斜体或下划线。 I'm a little confused on how to use the "active" class on twitter bootstrap's buttons to toggle functions such as adding different font styles to words in a textarea.
关于如何在twitter bootstrap的按钮上使用“active”类来切换函数,例如在textarea中为单词添加不同的字体样式,我有点困惑。
Here's my HTML: 这是我的HTML:
<span class="btn-group" data-toggle="buttons-checkbox">
<button class="btn btn-bold">Bold</button>
<button class="btn btn-italics">Italics</button>
<button class="btn btn-underline">Underline</button>
</span>
<textarea></textarea>
here's my JS: 这是我的JS:
$('.btn').click(function(){
if($('.btn-bold').hasClass('active')){
$('.btn-bold').toggle(
function() {
$('textarea').val($('textarea').val()+"<span style='font-weight:bold'>");},
function() {
$('textarea').val($('textarea').val()+"</span>");
}); //toggle
} //if
}); //click
I think i need to have code like this for each font-style: bold, italics, underline I toggle. 我想我需要为每种字体样式设置这样的代码:粗体,斜体,下划线切换。 But as you can see what I have for just making text bold is quite verbose (not to mention doesn't work) so there has to be a better way.
但正如你所看到的那样,仅仅使文本粗体化是非常冗长的(更不用说不起作用)所以必须有更好的方法。 Any thoughts would be greatly appreciated.
任何想法将不胜感激。
A better way to go about editing content would be to use the contentEditable
attribute, since it has a great support across browsers and a great selection of commands ( execCommand
) one can execute to edit content out, more information here on the execCommand
. 编辑内容的更好方法是使用
contentEditable
属性,因为它对浏览器有很好的支持,并且可以执行大量命令( execCommand
)来编辑内容,更多信息请execCommand
。
Here is a short demo i made about how to go about it: 这是一个关于如何进行的简短演示:
Relevant code: 相关代码:
JS JS
var current;
$(function() {
$("div[contenteditable]").focus(function() {
current = this;
});
// bold
$('.btn-bold').click(function() {
document.execCommand('bold', false, null);
$(current).contents().focus();
});
//italics
$('.btn-italics').click(function() {
document.execCommand('italic', false, null);
$(current).contents().focus();
});
//underline
$('.btn-underline').click(function() {
document.execCommand('underline', false, null);
$(current).contents().focus();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.