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.
以上是如何在 JavaScript 中比較顏色而不直接比較背景顏色?的詳細內容。更多資訊請關注PHP中文網其他相關文章!