【问题标题】:Change icon if a div has an specific background color如果 div 具有特定的背景颜色,则更改图标
【发布时间】:2018-03-24 00:37:17
【问题描述】:

嗨,我希望你能帮助我,我有一个进度条,其中有一些 PNG pin 图标必须根据另一个 div 的颜色从活动 pin 图像更改为非活动 pin 图像这是我在做什么,但它似乎没有为了工作,我学习了 JavaScript 和 Jquery,所以我不知道我是否做错了什么。

谢谢:)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

  <style>
    .quadrant {
      border-radius: 5px;
      border: .5px solid #d8d8d6;
      padding: 10px;
      margin-bottom: 20px;
    }

   .quadrant > p {
      text-align: center;
      font-family: Segoe, "Segoe UI", "DejaVu Sans", "Trebuchet MS", Verdana, "sans-serif";
      font-size: 20pt;
      color: #ffffff;
      font-weight: 700;
    }

    img {
      display: block;
      margin-left: auto;
      margin-right: auto;
      margin-bottom: 10px;
      margin-top: 10px;
    }

    .progress {
      width: 100%;
      height: 25px;
      background-color: #F1F1F1;
      box-shadow: 1px 1px 1px 1px #d8d8d6;
    }

    .bar {
      width: 25%;
      height: 25px;
      background-color: #003E8B;
    }

    .number {
      border-radius: 10px;
      border: 5px solid #ffffff;
      height: auto;
      margin-left: auto;
      margin-right: auto;
      color: #ffffff;
      font-weight: 700;
      text-align: center;
      margin-top: 10px;
      padding-top: 15px;
    }

    .number:hover {
      opacity: 0.8;
    }

    .number > p {
      font-size: 12px;
    }

    .color-pin {
      float: right;
    }
  </style>
</head>
<body>

  <div class="container">
    <div class="row">
      <div class="col-lg-4 col-md-4 col-sm-12 col--xs-12">
        <div class="row">
          <h3>Diagnostico en</h3>
        </div>
        <br><br>
        <div class="row">
          <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <div class="quadrant" style="background-color: #009BF3;">
              <img src="icons/instutucional.png" alt="Desarrollo Institucional para un Buen Gobierno" class="img-responsive" />
              <p>20%</p>
            </div>
          </div>
          <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <div classs="quadrant">
              <div class="quadrant" style="background-color: #007305;">
                <img src="icons/economico.png" alt="Desarrollo Institucional para un Buen Gobierno" class="img-responsive" />
                <p>40%</p>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <div classs="quadrant">
              <div class="quadrant" style="background-color: #EA8C1C;">
                <img src="icons/economico.png" alt="Desarrollo Institucional para un Buen Gobierno" class="img-responsive" />
                <p>40%</p>
              </div>
            </div>
          </div>
          <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
            <div classs="quadrant">
              <div class="quadrant" style="background-color: #21AAA0;">
                <img src="icons/economico.png" alt="Desarrollo Institucional para un Buen Gobierno" class="img-responsive" />
                <p>40%</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
        <div class="row">
          <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
            <!---<img src="icons/pin_insitucional.png" class="color-pin" id="institucional">--->
          </div>
          <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
            <img src="icons/pin_inactivo_economico.png" class="color-pin" id="economico">
          </div>
          <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
            <img src="icons/pin_inactivo_social.png" class="color-pin" id="social">
          </div>
          <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
            <img src="icons/pin_inactivo_naturaleza.png" class="color-pin" id="naturaleza">
          </div>
        </div>
        <div class="row">
          <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <div class="progress">
              <div class="bar">
              </div>
            </div>
          </div>
        </div>
        <hr>
        <div class="row">
          <h2>Consejos de Uso</h2>
          <p>Comienza por contestar primero todas las variables y después sube las evidencias conforme las obtengas.</p>
        </div>
        <div class="row">
          <div class="col-lg-3 col-md-3 col-sm-12 col-xs-12 number" style="background-color: #d8d8d6; cursor: pointer;" id="btn-institucional">
            <p>1</p>
            <img src="icons/institucional.png" width="50%">
            <p>Desarrollo Institucional para un Buen Gobierno</p>
          </div>
          <div class="col-lg-3 col-md-3 col-sm-12 col-xs-12 number" style="background-color: #007305; cursor: pointer;">
            <p>2</p>
            <img src="icons/economico.png" width="50%">
            <p>Desarrollo Económico Sostenible</p>
          </div>
          <div class="col-lg-3 col-md-3 col-sm-12 col-xs-12 number" style="background-color: #EA8C1C; cursor: pointer;">
            <p>3</p>
            <img src="icons/social.png" width="50%">
            <p>Desarrollo Social Incluyente</p>
          </div>
          <div class="col-lg-3 col-md-3 col-sm-12 col-xs-12 number" style="background-color: #21AAA0; cursor: pointer;">
            <p>4</p>
            <img src="icons/natural.png" width="50%">
            <p>Desartrollo Ambiental Sostenible</p>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" 
          crossorigin="anonymous"></script>

  <!-- Include all compiled plugins (below), or include individual files as needed -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" 
          crossorigin="anonymous"></script>

  <script>
    var color= $"btn-institucional");
        if( color.css('background-color') == "rgb(216,216,214)"){
        document.getElementById("institucional").src="icons/pin_inactivo_insitucional.png";
      } else {
        document.getElementById("institucional").src = "icons/pin_insitucional.png";
      }
  </script>
</body>
</html>

【问题讨论】:

  • 您的代码看起来不错。确保脚本位于关闭 body 标记之前,以便在它运行时,HTML 将被解析到内存中。
  • 请把整个html贴出来看看有没有其他问题
  • 已发布!感谢您的帮助!
  • 检查您的开发者控制台 (F12)。你至少有一个错误:var color= $"btn-institucional");

标签: javascript jquery html css image


【解决方案1】:

我发现了两个问题:

  • 您忘记将 ID institucional 添加到您的 img dom。应该是:

  • document.getElementById("btn-institucional").style.backgroundColor 为您提供 rgb 的颜色,而不是十六进制的颜色。在您的代码中,它返回的值为rgb(216, 216, 214)

您可以使用 rgb2hex 实用功能:

function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\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]);
}

source

这是example

console.log(document.getElementById("btn-institucional").style.backgroundColor); // returns rgb(216, 216, 214)

function rgb2hex(rgb) {
    if (/^#[0-9A-F]{6}$/i.test(rgb)) return rgb;

    rgb = rgb.match(/^rgb\((\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]);
}

let backgroundColor = rgb2hex(document.getElementById("btn-institucional").style.backgroundColor)

if( backgroundColor == "#d8d8d6") {
	document.getElementById("institucional").src = "http://www.ptahai.com/wp-content/uploads/2016/06/Best-Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg";
}
    <div class="row">

        <div class="col-lg-3 col-md-3 col-sm-12 col-xs-12 number" style="background-color: #d8d8d6; cursor: pointer;" id="btn-institucional">

            <p>1</p>

            <img id="institucional" src="institucional" src="https://www.w3schools.com/howto/img_fjords.jpg" width= "50%">

            <p>Desarrollo Institucional para un Buen Gobierno</p>   



        </div>

【讨论】:

  • 这应该是一条评论。
  • 哇!感谢您的回答,它奏效了! :D,但是如果你有时间的话,我是新手,你能解释一下为什么它会起作用吗?你是怎么做到的?谢谢:D!!
  • 我修复了我在回答中解释的两个问题,并且成功了 :)
  • 基本上,重新陈述我在回答中提到的内容,1.因为您没有为 img 标签设置iddocument.getElementById("institucional") 找不到目标img DOM。 2. 因为 document.getElementById("btn-institucional").style.backgroundColor 为您提供 rgb 中的颜色(有多种表示颜色值的方法。rgb 是其中之一,hex 是另一种。你应该这样做a google search for both)因为是用rgb表示的,但是你是用同一种颜色比较,但是用hex('#d8d8d6')表示,它们不匹配而且里面的语句if没得到执行。
  • 哦,好的,我怎样才能为每个引脚和按钮制作它,以便它们在 btn 颜色变化时发生变化?
【解决方案2】:

.style.backgroundColor 返回 rgb( 字符串,而不是 #xxxxxx 字符串。您必须解析 rgb( 字符串的数字并将它们转换为适当的十六进制字符串,如下所示:

const rgb = document.getElementById("btn-institucional").style.backgroundColor;
const rgbNums = rgb.match(/\((.+)\)/)[1].split(', ');
const rgbHex = rgbNums.map(num => {
  const numStr = Number(num).toString(16);
  if (numStr.length === 1) return '0' + numStr;
  return numStr;
});
const hexStr = '#' + rgbHex.join('');
console.log(hexStr);

if(hexStr == "#d8d8d6"){ 
  console.log('set src');
  document.getElementById("institucional").src="icons/pin_inactivo_insitucional.png";     
}
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
    <img src="icons/pin_insitucional.png" class="color-pin" id="institucional">
</div>

<div class="row">
  <div class="col-lg-3 col-md-3 col-sm-12 col-xs-12 number" style="background-color: #d8d8d6; cursor: pointer;" id="btn-institucional">     
  <p>1</p>          
  <img src="icons/institucional.png" width= "50%">
  <p>Desarrollo Institucional para un Buen Gobierno</p> 
</div>

【讨论】:

    【解决方案3】:

    这里有语法错误:var color= $"btn-institucional");

    应该是:var color= $("btn-institucional");

    而且,当您获得 background-color CSS 属性值时,它会以 rgb 字符串的形式返回,每个逗号后都有空格:

    // Notice that there will be spaces after each comma in the result
    console.log($("div").css("color")); // rgb(255, 255, 0)
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div style="color:#ff0;">test</div>

    您可以调整要与之比较的 rgb 字符串,也可以简单地提取 style 属性的值,该值将作为写入 HTML 的十六进制值返回:

    // This is a bit longer, but shows that you can get the original hex value
    
    // Get the "style" attribute, split its value where the colon is and return the second part of the 
    // resulting array.
    console.log($("div").attr("style").split(":")[1]);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div style="color:#ff0;">test</div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 2021-03-07
      • 2019-04-21
      • 1970-01-01
      • 2012-05-23
      • 2014-12-12
      • 2021-03-25
      相关资源
      最近更新 更多