如何使用jquery使文本变为粗体,斜体和下划线

cod*_*der 14 css jquery

我现在有三个复选框和一个文本框如果我在文本框中写一些东西并检查粗体复选框,文本应该以粗体效果出现,并且类似斜体和下划线而不回发(即它应该立即反映所选效果).

这是我的代码:

Bold:<input type="checkbox" value=""/>
Italic:<input type="checkbox" value=""/>
Underline:<input type="checkbox" value=""/>

<input type="text" value="">
Run Code Online (Sandbox Code Playgroud)

dSq*_*red 41

您可以执行以下操作:

<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>
Run Code Online (Sandbox Code Playgroud)

在这里小提琴:http://jsfiddle.net/tyfsf/

希望能帮助到你!


War*_*Fox 7

你可以使用简单的CSS和一些jQuery代码来做到这一点.

1.首先定义级联样式表类

<style type="text/css">
.bold {
 font-weight:bold;
}
.italic {
font-style:italic;
}
.underline {
    text-decoration: underline;
}
</style>
Run Code Online (Sandbox Code Playgroud)

2.加载jQuery

<script type="text/javascript" src="jquery.js"></script>
Run Code Online (Sandbox Code Playgroud)

3.编写切换类的功能

<script type="text/javascript">
$(document).ready(function () {
    $('.selector').click(function () {
        var checked = $(this).is(':checked');
        var value = $(this).attr('value');
        if(checked) {
            $('#box').addClass(value);
        } else {
            $('#box').removeClass(value);
        }
    });     

});
</script>
Run Code Online (Sandbox Code Playgroud)

5.Modified html

Bold:<input class='selector' type="checkbox" value="bold"/>
Italic:<input class='selector' type="checkbox" value="italic"/>
Underline:<input class='selector' type="checkbox" value="underline"/>
<br>
<input id="box" type="text" value="">
<br>
Run Code Online (Sandbox Code Playgroud)

jsfiddle链接:http://jsfiddle.net/deepumohanp/t2wKP/