简体   繁体   English

jQuery的Changin DIV背景色

[英]Changin DIV background color with jQuery

I have two DIV, and i want to change DIV color to green when its clicked (its working). 我有两个DIV,并且单击它时(它可以工作),我想将DIV颜色更改为绿色。 Im counting the clicks on div, and i want to stop counting if the DIV is already green. 我正在计算div上的点击次数,如果DIV已经为绿色,我想停止计数。

 var counter = 0; $(function() { $(".tile").click(function() { if ($(this).css('background-color') == 'rgb(250,0,0)') { $(this).css('background-color', '#008000'); counter++; $(this).append("/" + counter); } else { alert("Already colored!"); } }); }); 
 div { width: 90vh; height: 10vh; margin: auto; border: 3px solid black; padding: 25px 25px 25px 25px; background-color: rgb(250, 0, 0); display: table-cell; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='tile'></div> <div class='tile'></div> 

So, if the background is red (250,0,0) then recolor the div to green and change div text to 1. But if the div is not red (so already colored), and if i clicked on the green div then show the alert message. 因此,如果背景为红色(250,0,0)则将div重新着色为绿色,并将div文本更改为1。但是,如果div不是红色(已经着色),并且如果我单击绿色div,则显示警报消息。 Any ideas how can I fix that? 有什么想法我该如何解决? I guess with my IF is wrong. 我想我的IF是错误的。

Use CSS classes when you want to add/remove styling: 要添加/删除样式时,请使用CSS类:

CSS 的CSS

.red-bg
{
   background-color: red;
}

.green-bg
{
   background-color: green;
}

Javascript Java脚本

if ($(this).hasClass('red-bg'))
{
    $(this).removeClass('red-bg')
           .addClass('green-bg');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM