Home  >  Article  >  Web Front-end  >  How to compare colors in JavaScript without directly comparing background colors?

How to compare colors in JavaScript without directly comparing background colors?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-15 01:15:02470browse

How to compare colors in JavaScript without directly comparing background colors?

How to compare colors in JavaScript?

Your code compares the background color of an element to a specific value (#ECECF4). However, this approach is not recommended as it tightly couples the business logic with the presentation.

Instead, consider keeping the logic in JavaScript and using classes to visually represent different states. This allows you to separate the styling from the business logic and ensure that the presentation is handled solely by CSS.

For example, you can use jQuery to toggle an 'active' class when an element is clicked:

$(".list").on("click", "li", function() {
  $(this).toggleClass('active');
});

Then, define the corresponding CSS to change the background color of active elements:

.list {
  width: 100%;
  padding: 0;
}
.list li {
  padding: 5px 10px;
  list-style: none;
  cursor: pointer;
}
.list li:hover {
  background-color: rgba(0, 0, 0, 0.05);
}
.list li.active {
  background-color: #eeeecc;
}

This approach allows you to manipulate the presentation without modifying the business logic, leading to cleaner and more maintainable code.

The above is the detailed content of How to compare colors in JavaScript without directly comparing background colors?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn