Изменить стиль кнопки HTML, когда щелчок не работает в Javascript - PullRequest
0 голосов
/ 03 мая 2018

Я хочу изменить цвет кнопки при нажатии на кнопку. Это код, который я использовал.

function abc() {
    var color = document.getElementById("btn").style.background - color;
    if (background - color === "#c1580b")
        document.getElementById("btn").style.cssText = "box-shadow: 0px 0px 0px 3px #173B0B; background-color: #173B0B; color:#459c5c";
    else
        document.getElementById("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;
}
<button id="btn" class="btn" onclick="abc()">Pause</button>

Но это не работает.

Ответы [ 4 ]

0 голосов
/ 03 мая 2018

Здесь у вас есть рабочий код.

Я бы посоветовал вам избежать встроенного 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>
0 голосов
/ 03 мая 2018

Я не совсем понял эту часть background - color, но чтобы проверить фон в шестнадцатеричном формате, нужно перейти от гекса к rgb.

Здесь можно увидеть больше примеров того, как передать hex в rgb - https://stackoverflow.com/a/4090628/8098173

Вот пример того, что вы хотите.

function abc() {
    var bt = document.getElementById('btn');
    var style = bt.currentStyle || window.getComputedStyle(bt);
    var bcolor = rgb2hex(style.backgroundColor);
    if (bcolor === '#c1580b') {
        bt.style.cssText = "box-shadow: 0px 0px 0px 3px #173B0B; background-color: #173B0B; color:#459c5c";
    } else {
        bt.style.cssText = "box-shadow: 0px 0px 0px 3px #c1580b; background-color: #c1580b; color:#ffb734";
    }
}

// pass rbg to hex
function rgb2hex(rgb) {
    if (  rgb.search("rgb") == -1 ) {
        return rgb;
    } else {
        rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
      function hex(x) {
        return ("0" + parseInt(x).toString(16)).slice(-2);
      }
      return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
    }
}
.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;
}
<button id="btn" class="btn" onclick="abc()">Pause</button>
0 голосов
/ 03 мая 2018

если вы всегда используете этот цвет в формате HEX (# c1580b), то есть:

function abc() {
    var elm = document.getElementById( 'btn' );
    var color = window.getComputedStyle( elm ).backgroundColor;

    if ( color === 'rgb(193, 88, 11)' )
        elm.style.cssText = 'box-shadow: 0 0 0 3px #173B0B; background-color: #173B0B; color: #459c5c'
    else
        elm.style.cssText = 'box-shadow: 0 0 0 3px #c1580b; background-color: #c1580b; color: #ffb734'
}
0 голосов
/ 03 мая 2018

Ваш код содержит некоторую логическую ошибку. Условие if не имеет смысла: background - color означает «вычесть значение color значению background (которое кажется неопределенным).

Чтобы получить цвет фона кнопки, вам нужно следующее background = document.getElementById("btn").style.backgroundColor; if (background === "#c1580b")

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...