<script language="javascript">
$(function(){
$("#changer").on("click",function(e){
e.preventDefault();
var body = document.getElementById("section2"),
green = "rgb(0, 128, 0)",
white = "rgb(255, 255, 255)";
if(body.css("backgroundColor") !== green){
body.css("backgroundColor",green);
}else{
body.css("backgroundColor",white);
}
});
})
</script>
和html
<div id="section2" align="center">
<a href="#" id="changer">Click me</a>
</div>
答案 0 :(得分:2)
原生HTML元素没有css
方法,这是jQuery方法。因此,body
的代码应为:
var body = $("#section2"),
整个演示:
$(function () {
$("#changer").on("click", function (e) {
e.preventDefault();
var body = $("#section2"),
green = "rgb(0, 128, 0)",
white = "rgb(255, 255, 255)";
if (body.css("backgroundColor") !== green) {
body.css("backgroundColor", green);
} else {
body.css("backgroundColor", white);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="section2" align="center">
<a href="#" id="changer">Click me</a>
</div>
但是,比较背景颜色的CSS属性值非常不可靠。你最好比较/检查课程:
$("#changer").on("click", function (e) {
e.preventDefault();
$("#section2").toggleClass('green white');
});
.green {background-color: rgb(0, 128, 0);}
.white {background-color: rgb(255, 255, 255);}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="section2" class="white" align="center">
<a href="#" id="changer">Click me</a>
</div>
答案 1 :(得分:0)
使用JQuery引用项目:
$(function () {
$("#changer").on("click", function (e) {
e.preventDefault();
var body = $("#section2"),
green = "rgb(0, 128, 0)",
white = "rgb(255, 255, 255)";
if (body.css("backgroundColor") !== green) {
body.css("backgroundColor", green);
} else {
body.css("backgroundColor", white);
}
});
})
答案 2 :(得分:0)
答案 3 :(得分:0)
尝试使用CSS类控制$("#section2")
background-color属性:
#section2.green {
background-color: green;
}
#section2.white {
background-color: white;
}
所以,使用jQuery添加背景颜色:
$(function () {
$("#changer").on("click", function (e) {
e.preventDefault();
var body = $("#section2");
if (body.hasClass('green')) {
body.removeClass('green')
.addClass('white');
} else {
body.removeClass('white')
.addClass('green');
}
});
})
答案 4 :(得分:0)
接近工作后,
{{1}}