当从下拉表单中选择选项时,我尝试使用attr() jQuery方法更改h1元素的类名。我希望类名更改为访问不同的CSS属性(字体)
我想我还没有深入到DOM中去改变类吗?
function myFontStyle() {
$('#font').on("change", function() {
var fontChange = this.value
console.log(this.value);
$('h1').attr('class', + fontChange);
});
}
myFontStyle();.handwriting{
font-family: 'Pacifico', cursive;
}
.sketch{
font-family: 'Fredericka the Great', cursive;
}
.print{
font-family: 'Sigmar One', cursive;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="font">Choose font</label>
<select name="font" id="font">
<option value="handwriting">Handwriting</option>
<option value="sketch">Sketch</option>
<option value="print">Print</option>
</select>
<div class="card celadonBackground">
<div id="coverImage">
<img src="assets/birthday.jpg"/>
</div>
<div class="noBorder">
<h1 class="sketch">Happy birthday to you</h1>
</div>
</div>
发布于 2017-11-16 09:25:13
将$('h1').attr('class', +fontChange);更改为
$('h1').attr('class', fontChange);
function myFontStyle() {
$('#font').on("change", function() {
var fontChange = this.value
//console.log(this.value);
$('h1').attr('class', fontChange);
console.log('h1 has now class: ', $('h1').attr('class'))
});
}
myFontStyle();<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="font">Choose font</label>
<select name="font" id="font">
<option value="handwriting">Handwriting</option>
<option value="sketch">Sketch</option>
<option value="print">Print</option>
</select>
<div class="card celadonBackground">
<div id="coverImage">
<img src="assets/birthday.jpg"/>
</div>
<div class="noBorder">
<h1 class="sketch">Happy birthday to you</h1>
</div>
</div>
发布于 2017-11-16 09:29:59
您可以根据您的jQuery版本使用attr或prop:
$(selector).attr('class', 'className'); // jQuery < 1.6
$(selector).prop('class', 'className'); // jQuery >= 1.6向现有类添加类
var classes = $(selector).prop('class');
$(selector).prop('class', classes + ' className');删除类
var classes = $(selector).prop('class').replace('notNeededClass', '');
$(selector).prop('class', classes);但是jQuery直接提供classManipulation
$(selector).addClass('className');
$(selector).removeClass('className');
$(selector).toggleClass('className');发布于 2017-11-16 09:26:20
语法错误
function myFontStyle() {
$('#font').on("change", function() {
var fontChange = this.value
console.log(this.value);
$('h1').attr('class', fontChange);
});
}
myFontStyle(); https://stackoverflow.com/questions/47325791
复制相似问题