【发布时间】:2021-04-03 04:14:04
【问题描述】:
我有一些 JS 代码会将我的代码变为粗体、斜体或带有下划线的用户输入,因此如果用户选中粗体,则文本将变为粗体。 代码如下:
$('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');
}
});
body {
background-color: #5f5959;
color: #000000;
}
textarea[type=text], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
textarea[type=submit] {
width: 100%;
background-color: #f9f9f9;
color: 000000;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
textarea[type=submit]:hover {
background-color: #908989;
}
div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
<form style="font-family: 'Poppins', sans-serif; color: #f9f9f9;">
Bold:<input name="textStyle" type="checkbox" value="bold"/>
<br>
Italic:<input name="textStyle" type="checkbox" value="italic"/>
<br>
Underline:<input name="textStyle" type="checkbox" value="underline"/>
</form>
<div style="margin-left: 240px; width: 1000px; height: 665px;">
<p><center style="font-family: 'Poppins', sans-serif; font-size: 13px;">When submit, your text will clear and your blog will be published!</center></p>
<textarea type="text" placeholder="Title" style="font-family: 'Poppins', sans-serif;"></textarea>
<form style="font-family: 'Poppins', sans-serif;">
<textarea name="styledText" type="text" style="font-family: 'Poppins', sans-serif; border-width: 2px; border-style: solid; outline: none; border: none; height: 445px;"></textarea>
<input style="height: 50px; width: 1000px; font-family: 'Poppins', sans-serif; border-radius: 7px;" value="Submit" type="submit">
</form>
</div>
它给了我一个错误,它不是粗体/斜体/下划线。我认为这是因为 JS 代码正在检查输入,但标签是 textarea。有什么办法可以让它同时接受吗?我希望空白的大区域用用户输入加粗/斜体/下划线。谢谢!
【问题讨论】:
-
您可以查询
textarea?$('textarea[name=styledText]') -
如果你想让 jQuery 在同一个函数中检查两个选择器,你可以使用
$('input[name="styledText"], textarea[name="styledText"]')甚至$('[name="styledText"]')
标签: javascript html jquery css