jquery - CSS-property 'background' not working in 'if.. else' -
i can not create css-property 'background' work when using in 'if.. else' - statement. tried possible combinations of 'background-color' , backgroundcolor' in both css , jquery, nil working.
the funny thing when exchanging 'if..' property fx ('width') == '500px' working fine.
are there special thing should know when using 'background'? heres code doesn't work - div turns yellowish when clicking thought should become pink..
.box { width: 500px; height: 200px; background: red; } <script src='http://code.jquery.com/jquery-latest.min.js'></script> <script> $(document).ready(function() { $('.box').click(function(){ if ($('.box').css('background') == 'red') { $('.box').css('background', 'pink'); } else { $('.box').css('background', 'yellow'); } }); }); </script>
answer - original reply showdev, think reflects question improve - help future visitors:
$('.box').click(function() { if ($(this).css('background-color') == 'rgb(255, 0, 0)') { $(this).css('background-color', 'pink'); } else { $(this).css('background-color', 'yellow'); } });
the css background
shorthand several individual background properties including background-clip, background-color, background-image, background-origin, background-position, background-repeat, background-size, , background-attachment.
as result, value of background
returned rgb(255, 192, 203) none repeat scroll 0% 0% / auto padding-box border-box
.
you can utilize background-color
instead, jquery returns background-color
values in rgb rather hex. you'll need match rgb values rather hex or words ("red").
also, changed references within click handler utilize $(this)
rather selecting box again. allows more flexibility when multiple boxes on page.
class="snippet-code-js lang-js prettyprint-override">$(document).ready(function() { $('.box').click(function() { $this = $(this); $this.css('background-color', $this.css('background-color') == 'rgb(255, 0, 0)' ? 'pink' : 'yellow'); }); });
class="snippet-code-css lang-css prettyprint-override">.box { width: 500px; height: 50px; background-color: red; } .box.blue { background-color: blue; }
class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="box"></div> <div class="box blue"></div>
regarding css colors rgb:
"computed value: if value translucent, computed value rgba() corresponding one. if isn't, rgb() corresponding one." -color - css | mdn
can forcefulness backgroundcolor
[to homecoming in] hexadecimal format?
jquery
No comments:
Post a Comment