简体   繁体   中英

jQuery - How to change background color according to item that has class “selected”

I have this menu with a list of options of colors. One of the colors is "blue" and has a class of "selected", and my background-color is "blue". I want to change the background color according to which color has the class of selected. I already know how to change the class, but now I want to know how to identify the class "selected" with the coordinating color.

Here's my code:

:

var coorColor;
$(".item").click(function() {
    $(".item").removeClass("selected");
    $(this).addClass("selected");
    $("body").css("background", coorColor);
});

// THIS IS THE PART I NEED HELP WITH

if($(".item.red.selected")) {
    coorColor = "red";
}

if($(".item.green.selected")) {
    coorColor = "green";
}

etc...

<ul>
    <li class="item blue selected">Blue</li>
    <li class="item red">Red</li>
    <li class="item green">Green</li>
</ul>

/* because the item "blue" is selected by default the body's bg-color is blue by default but will change according to jQuery */

body {
    background: blue;
}

.selected {
    text-shadow: 1px 1px 10px #565756;
}

You can check for the class in the selected element:

$(".item").click(function() {
  $(".item").removeClass("selected");
  $(this).addClass("selected");

  if ($(this).hasclass("blue")) {
    coorColor = "blue";
  } else if ($(this).hasclass("red") {
    coorColor = "red";
  }

  $("body").css("background", coorColor);
});

A slightly simpler approach would be to use data- attributes:

<ul>
    <li data-color="blue"  class="item blue selected">Blue</li>
    <li data-color="red"   class="item red">Red</li>
    <li data-color="green" class="item green">Green</li>
</ul>

Your code would then become:

var coorColor = $('.item.selected').data('color');

If you are going to have only those classes for the item you could do this

$(".item").click(function() {
    $(".item").removeClass("selected");

    /* this will eliminate the unwanted classes leaving just the color class */
    var coorColor = $(this).attr('class').replace(new RegExp('item|anotherClass| ', 'g'), '');

    $(this).addClass("selected");
    $("body").css("background", coorColor);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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