[英]Onclick change background color
這是我的Jquery代碼:
$("#test").click(function() {
if($(this).css("background-color")=="#FFFFFF")
$(this).css("background-color","blue");
else
if($(this).css("background-color")=="blue")
$(this).css("background-color","#FFFFFF");
});
這是HTML:
<div id="test">
click me!
</div>
你能解釋一下為什么它不起作用嗎?
非常感謝你
你也忘了把JQuery包含在你的小提琴中
$(function(){
$('#test').click(function() {
if($(this).css('background-color') == 'rgb(255, 255, 255)')
$(this).css('background-color', 'blue');
else
if($(this).css('background-color') == 'rgb(0, 0, 255)')
$(this).css('background-color', '#FFFFFF');
});
});
替代方式,如果您願意:
.blue {
background-color: blue !important;
}
$(function(){
$('#test').click(function() {
$(this).toggleClass('blue');
});
});
像這樣用它:
$("#test").click(function() {
if($(this).css("background-color")=="rgb(255, 255, 255)")
$(this).css("background-color","blue");
else
if($(this).css("background-color")=="rgb(0, 0, 255)")
$(this).css("background-color","#FFFFFF");
});
原因是css()
函數返回rgb
格式的顏色,這對你的條件不起作用。
創建一個不依賴於顏色的切換功能,因為返回的樣式在不同瀏覽器中可能不一致,具體取決於它們是否支持rgb / rgba / hsl等。
$("#test").on('click', function() {
var flag = $(this).data('flag');
$(this).css('background-color', flag ? '#fff' : 'blue');
$(this).data('flag', !flag);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.