如何使用jQuery将文本设置为粗体,斜体和下划线
问题描述:
我现在有三个复选框和一个文本框,如果我在文本框中写了一些东西并选中了粗体复选框,则文本应显示为粗体效果,并且类似斜体和下划线,且不带回发(即,应立即以所选效果反映出来).
I have three checkboxes and a textbox now If I write something in textbox and check the bold checkbox the text should appear with bold effect and similarly italic and underline without postback(i.e it should reflect immediately with the selected effect).
这是我的代码:
Bold:<input type="checkbox" value=""/>
Italic:<input type="checkbox" value=""/>
Underline:<input type="checkbox" value=""/>
<input type="text" value="">
答
您可以执行以下操作:
<form>
Bold:<input name="textStyle" type="checkbox" value="bold"/>
Italic:<input name="textStyle" type="checkbox" value="italic"/>
Underline:<input name="textStyle" type="checkbox" value="underline"/>
<input name="styledText" type="text" value="">
</form>
<script type="text/javascript">
$('input[name="textStyle"]').change(function(){
if ($(this).val() == 'bold'){
if ($(this).is(':checked')) $('input[name="styledText"]').css('font-weight', 'bold');
else $('input[name="styledText"]').css('font-weight', 'normal');
}
else if ($(this).val() == 'italic'){
if ($(this).is(':checked')) $('input[name="styledText"]').css('font-style', 'italic');
else $('input[name="styledText"]').css('font-style', 'normal');
}
else if ($(this).val() == 'underline'){
if ($(this).is(':checked')) $('input[name="styledText"]').css('text-decoration', 'underline');
else $('input[name="styledText"]').css('text-decoration', 'none');
}
});
</script>
在这里拨弄: http://jsfiddle.net/tyfsf/
希望有帮助!