javascript - 2 个用于更改颜色不透明度的按钮(Javascript)

标签 javascript addeventlistener

我正在尝试解决两个按钮正确工作的问题(我将它们称为 btnleftbtnright)。我将使用它们来更改随机颜色的不透明度/alpha channel (例如 hsl(x, y%, z%, 1) -> hsl(x, y%, z%, 0.8))。

a 变量用于设置不透明度值,btnleft 用于降低不透明度,btnright 用于提高不透明度。当我单击左/右按钮时,主函数 alphaValue 不起作用(并且我在 WWW 控制台上没有看到任何错误)。

HSLinStringAlphahsl(hue, Saturation%, lumination%, opacity) 表示法。

下面我放置了我的代码(可能太长,但在不改变不透明度的情况下工作)。

感谢您的建议。

/* Nested functions with errors */

function colorChange() {

  function randomColor() {
    let Cmax = []; let Cmin = []; let Lum = []; let Delta = [];
    let Hue = []; let Sat = [];    
    let HueAngle = Math.round(60 * Hue);
    let SatInt = Math.round(100 * Sat);
    let LumInt = Math.round(100 * Lum);
    
/* Here is probably some mistake (wrong method of made function?) */  
    function FullHSLCode() {
      for (let i = 0; i < indexValue.length / 3; i++) {
        HSLinString[i] = `hsl(${HueAngle[i]}, ${SatInt[i]}%, ${LumInt[i]}%)`;
      }
      return HSLinString;
    }
    FullHSLCode();
  }
  /* End of randomColor(), here I was tried to made closure */
randomColor();
  
  var a = 1;
  var HSLinStringAlpha = [`hsla(${HueAngle[0]}, ${SatInt[0]}%, ${LumInt[0]}%, ${a})`];

/* alphaValue() doesn't work after move it outside randomColor() function - WWW console shows that HueAngle, SatInt, LumInt variables aren't accessible */
  function alphaValue(HSLinStringAlpha, HueAngle, SatInt, LumInt, a) {
    if (this.id !== "btn1") {
      //if(button1.onclick === true) {
      if (this.id === "btnleft") {
        a -= 0.05;
      } else if (this.id === "btnright") {
        a += 0.05;
      }      
      HSLinStringAlpha.push(`hsla(${HueAngle[0]}, ${SatInt[0]}%, ${LumInt[0]}%, ${a})`);
      HSLinStringAlpha.shift();
    }
    return HSLinStringAlpha;
  }
  alphaValue();
  
  /* 
  let button1 = document.getElementById("btnleft");
  let button2 = document.getElementById("btnright");
  button1.disabled = false;
  button2.disabled = false;
  button1.addEventListener("click", alphaValue, false);
  button2.addEventListener("click", alphaValue, false);
  */
}

最佳答案

检查单击了哪个按钮,您不应该使用

if (button1.onclick === true)

但是使用像

if (this.id === 'btnleft')

window.addEventListener("DOMContentLoaded", colorChange);

function colorChange() {
  document.getElementById("btn1").addEventListener("click", randomColor, false);

  function randomColor() {
    let HEXColor = [];
    let HSLColor = [];
    let RGBinString = []; // defines color in rgb(num,num,num) style
    let HEXinString = []; // defines color in hexadecimal style
    let HSLinString = []; // defines color in hsl() style

    /* Randomize r,g,b numbers of colors in rgb(num,num,num) style */
    let indexValue = [];
    let colorArray = [];

    function RGBrandom() {
      for(let j = 0; j <= 8; j++) {
        indexValue[j] = Math.floor(Math.random() * 256);
        colorArray.push(indexValue[j]);
      }
      for(i = 0; i < 3; i++) {
        RGBinString[i] = `rgb(${indexValue[3*i]},${indexValue[3*i+1]},${indexValue[3*i+2]})`;
      }
      return RGBinString;
    }
    RGBrandom();

    // Calculate hex code string from rgb code
    function RGBtoHex(indexValue) {
      const HEXcolorValue = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "a", "b", "c", "d", "e", "f"];
      for(let i = 0; i < indexValue.length; i++) {
        if(indexValue[i] <= 15) {
          HEXColor.push(0, HEXcolorValue[indexValue[i]]);
        }
        else {
          HEXColor.push(HEXcolorValue[Math.floor(indexValue[i] / 16)], HEXcolorValue[(indexValue[i]) % 16]);
        }
      }
      return HEXColor;
    }

    let HEXFullColor = RGBtoHex(indexValue);

    function FullHEXCode() {
      for(let j = 0; j < HEXFullColor.length / 6; j++) {
        HEXFullColor[j] = HEXFullColor.slice(6 * j, 6 * j + 6);
        HEXinString[j] = HEXFullColor[j].join("");
        HEXinString[j] = `#${HEXinString[j]}`;
      }
      return HEXinString;
    }
    FullHEXCode();

    let RGBArray = [];

    function RGBvalueChange() {
      for(let j = 0; j <= 8; j++) {
        /* for Red indexes (j = 0, 3, 6, etc.) */
        if(j % 3 === 0) {
          RGBArray.push(indexValue[j] / 255);
        }
        /* for Green indexes (j = 1, 4, 7, etc.) */
        else if((j + 2) % 3 === 0) {
          RGBArray.push(indexValue[j] / 255);
        }
        /* for Blue indexes (j = 2, 5, 8, etc.) */
        else {
          RGBArray.push(indexValue[j] / 255);
        }
      }
      return RGBArray;
    }
    RGBvalueChange();

    let Cmax = [];
    let Cmin = [];
    let Lum = [];
    let Delta = [];
    let Hue = [];
    let Sat = [];
    let HuePercent = [];
    let SatInt = [];
    let LumInt = [];
    for(let i = 0; i < indexValue.length / 3; i++) {
      Cmin.push(Math.min(RGBArray[3 * i], RGBArray[3 * i + 1], RGBArray[3 * i + 2])); // 3 values
      Cmax.push(Math.max(RGBArray[3 * i], RGBArray[3 * i + 1], RGBArray[3 * i + 2])); // 3 values
      Lum.push((Cmax[i] + Cmin[i]) / 2); // 3 values
      Delta[i] = Cmax[i] - Cmin[i]; // 3 values
      if(Delta[i] === 0) {
        Hue.push(0); //Hue[i] === 0; 
        Sat.push(0); //Sat[i] === 0;
      }
      else {
        // Hue dependance from other parameters
        if(Cmax[i] === RGBArray[3 * i]) {
          Hue.push(((RGBArray[3 * i + 1] - RGBArray[3 * i + 2]) / Delta[i] + (RGBArray[3 * i + 1] < RGBArray[3 * i + 2] ? 6 : 0)));
        }
        else if(Cmax[i] === RGBArray[3 * i + 1]) {
          Hue.push((RGBArray[3 * i + 2] - RGBArray[3 * i]) / Delta[i] + 2);
        }
        else if(Cmax[i] === RGBArray[3 * i + 2]) {
          Hue.push((RGBArray[3 * i] - RGBArray[3 * i + 1]) / Delta[i] + 4);
        }
        else {
          Hue.push(0);
        }
        Sat[i] = Lum[i] > 0.5 ? (0.5 * Delta[i]) / (1 - Lum[i]) : Delta[i] / (2 * Lum[i]);
        Sat.push(Sat[i]);
      }
      HuePercent[i] = Math.round(60 * Hue[i]);
      SatInt[i] = Math.round(100 * Sat[i]);
      LumInt[i] = Math.round(100 * Lum[i]);
    }

    function FullHSLCode() {
      for(let j = 0; j < indexValue.length / 3; j++) {
        HSLinString[j] = `hsl(${HuePercent[j]}, ${SatInt[j]}%, ${LumInt[j]}%)`;
      }
      return HSLinString;
    }
    FullHSLCode();

    var a = 1;
    let HSLinStringAlpha = [`hsl(${HuePercent[0]}, ${SatInt[0]}%, ${LumInt[0]}%, ${a})`];
    let button1 = document.getElementById("btnleft");
    let button2 = document.getElementById("btnright");
    button1.disabled = false;
    button2.disabled = false;

    function alphaValue() {
      if(this.id !== 'btn1') {
        //if(button1.onclick === true) {
        if(this.id === 'btnleft') {
          a -= 0.05;
        }
        else {
          a += 0.05;
        }
        //console.log(a)
        HSLinStringAlpha[0] = [`hsl(${HuePercent[0]}, ${SatInt[0]}%, ${LumInt[0]}%, ${a})`];
        //HSLinStringAlpha.shift();
      }
      console.log(HSLinStringAlpha[0][0])
      return HSLinStringAlpha;
    }

    button1.addEventListener("click", alphaValue, false);
    button2.addEventListener("click", alphaValue, false);

    document.querySelector("p").innerHTML = [`${a} `, HSLinStringAlpha];

    // 3 random colors in every element (circle)
    document.getElementById("color1").value = HEXinString[0];
    document.getElementById("color2").value = HEXinString[1];
    document.getElementById("color3").value = HEXinString[2];

    document.getElementById("color4").value = RGBinString[0];
    document.getElementById("color5").value = RGBinString[1];
    document.getElementById("color6").value = RGBinString[2];

    document.getElementById("color7").value = HSLinStringAlpha[0];
    document.getElementById("color8").value = HSLinString[1];
    document.getElementById("color9").value = HSLinString[2];

    box1.style.backgroundColor = HSLinStringAlpha[0];
    box2.style.backgroundColor = HSLinStringAlpha[0];
    box3.style.backgroundColor = HSLinStringAlpha[0];
  }
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  height: 100vh;
  width: 100vw;
  background-color: lightgray;
  position: absolute;
}

.bigbox {
  min-height: 320px;
  width: 630px;
  position: absolute;
}

.box {
  height: auto;
  width: 33%;
  margin: 0 0 10px;
  background-color: lightgray;
  display: block;
  position: relative;
  float: left;
}

.colorbox {
  height: 150px;
  width: 150px;
  margin: 5px auto;
  border-radius: 50%;
  background-color: #234523;
  display: block;
}

.text {
  height: auto;
  width: 100%;
  display: block;
  float: left;
}

.shape {
  height: 1.75em;
  width: calc(100% - 3px);
  margin: 0 auto 5px;
  font-size: 18px;
  text-align: left;
  border: gray solid 1px;
  display: block;
}

p {
  display: inline-block;
  margin: 10px 5px;
  float:right; 
}

.arrowbox {
  height: 100%;
  width: 100%;
  margin: 0 auto;
  font-size: 20px;
  display: block;
  float: left;
}

.buttons {
  height: 100%;
  width: 40%;
  margin: 10px auto;
  display: block;
  float: left;
}

.testbutton {
  height: 100%;
  width: 40%;
  font-size: 20px;
  display: block;
  float: left;
}

.arrowbutton {
  height: 100%;
  width: 30%;
  font-size: 20px;
  display: block;
  float: left;
}

.buttonbox {
  height: 3.5em;
  width: 100%;
  font-size: 20px;
  display: block;
  clear: both;
}

#btn1 {
  height: 100%;
  width: 8.5em;
  margin: 0 auto;
  font-size: 20px;
  display: block;
}
<div class="container">
    <div class="bigbox">
      <div id="box4" class="box">
        <div id="box1" class="colorbox"></div>
        <div class="text">
          <input type="text" id="color1" class="shape" value="" size="12" maxlength="7" readonly="readonly" />
          <input type="text" id="color4" class="shape" value="" size="12" maxlength="7" readonly="readonly" />
          <input type="text" id="color7" class="shape" value="" size="12" maxlength="7" readonly="readonly" />
        </div>
      </div>
      <div id="box5" class="box">
        <div id="box2" class="colorbox"></div>
        <div class="text">
          <input type="text" id="color2" class="shape" value="" size="12" maxlength="15" readonly="readonly" />
          <input type="text" id="color5" class="shape" value="" size="12" maxlength="15" readonly="readonly" />
          <input type="text" id="color8" class="shape" value="" size="12" maxlength="15" readonly="readonly" />
        </div>
      </div>
      <div id="box6" class="box">
        <div id="box3" class="colorbox"></div>
        <div class="text">
          <input type="text" id="color3" class="shape" value="" size="12" maxlength="15" readonly="readonly" />
          <input type="text" id="color6" class="shape" value="" size="12" maxlength="15" readonly="readonly" />
          <input type="text" id="color9" class="shape" value="" size="12" maxlength="15" readonly="readonly" />
        </div>
      </div>
      <div class="buttonbox">
        <div class="arrowbox">
          <p>Yes, it's almost something what I'm looking for, but...Yeah you need some extra options - click "TEST" button below.</p>
          <div class="buttons">
            <button id="btnleft" class="arrowbutton">&#9668;</button>
            <button id="btncenter" class="testbutton">RESET</button>
            <button id="btnright" class="arrowbutton">&#9658;</button>
          </div>
        </div>
        <button id="btn1" onclick="colorChange();">Click for color !!!</button>
      </div>
    </div>
  </div>

关于javascript - 2 个用于更改颜色不透明度的按钮(Javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45533223/

相关文章:

javascript - jquery mobile 页面文本中的字符串搜索

javascript - 计算 JSON 中的键/值

javascript - 我在 html 中运行函数时遇到错误

canvas - 在 Canvas 上获取鼠标点击事件

javascript - addEventlistener 到 javascript 中的所有新对象

javascript - 下一个js中的HTTPS重定向

javascript - 将异步调用转换为同步?

javascript - 在事件监听器中使用 eval(myFunctionName) 作为回调的替代方法是什么?

JavaScript 事件监听器

javascript - 如何使用 Vanilla Javascript 检测元素的 scrollTop?