Здесь у вас есть рабочий код.
Я бы посоветовал вам избежать встроенного onclick="abc()"
и отдать предпочтение полностью отделенному коду, используя EventListener (это хорошо для удобства сопровождения).
С помощью Window.getComputedStyle () вы получаете цвет фона в RGBA; затем вы можете преобразовать его в код HEX с помощью простой функции, которую вы можете найти повсюду в Интернете, здесь я использовал одну из них. Итак, правильный способ получить цвет фона - window.getComputedStyle(btn, null)["backgroundColor"]
, тогда как, если вы хотите установить его, правильная форма будет document.getElementById("btn").style.backgroundColor = "#0000"
.
/**
* The code inside the function is run only when the DOM is ready.
* This is the only jQuery function used, all the rest is in vanillaJS.
*/
$(document).ready(function() {
/**
* rgb2hex
* Convert RGB to HEX.
* Source: https://jsfiddle.net/Mottie/xcqpF/1/light/
*
* @param {string} rgb
*/
var rgb2hex = function(rgb){
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
/**
* EventListener of btn click event
*/
document.getElementById("btn")
.addEventListener('click', function() {
// Save the btn into a var so you can use it later
var btn = document.getElementById("btn");
// Notice: getComputedStyle() to get the element background color
var color = window.getComputedStyle(btn, null)["backgroundColor"];
// Transform RGBa to HEX
var hex = rgb2hex(color);
// IF-ELSE with ternary operators
(hex === "#c1580b")
? btn.style.cssText = "box-shadow: 0px 0px 0px 3px #173B0B; background-color: #173B0B; color:#459c5c"
: btn.style.cssText = "box-shadow: 0px 0px 0px 3px #c1580b; background-color: #c1580b; color:#ffb734";
});
});
.btn {
background: #c1580b;
color: #ffb734;
width: 80px;
height: 80px;
line-height: 70px;
display: block;
border-radius: 50%;
text-align: center;
text-decoration: none;
border: 2px solid #000;
box-shadow: 0px 0px 0px 3px #c1580b;
font-size: medium;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<button id="btn" class="btn">Pause</button>
</body>
</html>