首页 > 解决方案 > 每次单击淡入淡出按钮都会使背景框不断淡入淡出

问题描述

全新的编码。每次单击时,都试图让“淡入淡出”按钮淡出一点。我已经使用此代码来扩大和缩小盒子,并且我试图对不透明度做同样的事情:

document.getElementById("growbutton").addEventListener("click", function() {
  var growVariable = 10;
  var newValueHeight = parseInt(document.getElementById("box").style.height)

  document.getElementById("box").style.height = newValueHeight + growVariable + "px";

  var newValueWidth = parseInt(document.getElementById("box").style.width)
  document.getElementById("box").style.width = newValueWidth + growVariable + "px";

});


document.getElementById("fadebutton").addEventListener("click", function() {
  var opVariable = .2;
  var newOpValue = parseInt(document.getElementById("box").style.opacity)
  document.getElementById("box").style.opacity = newValueHeight - opVariable;
});
<div id="box" style="height: 150px; max-height: 600px; min-height: 5px; width:150px; max-width: 600px; min-width: 5px; background-color:orange; margin:50px"></div>
<button id="fadebutton">Fade</button>
<button id="growbutton">Grow</button>

你能告诉我我错过了什么,所以每次点击该框都会消失 0.2 吗?

标签: javascripthtml

解决方案


您现有的代码会产生错误:Uncaught ReferenceError: newValueHeight is not defined. 有几个问题:

  1. 您是在引用newValueHeight而不是newOpValue偶然。
  2. parseInt()将返回一个整数,即如果当前不透明度为 0.8,则parseInt(0.8)返回1. 您需要使用parseFloat()来获取浮点数。
  3. 最初,style.opacityundefined因为它尚未设置。opValue = ... || 1如果尚未设置,您应该使用它默认为 1。

let box = document.getElementById('box'),
    fadeBtn = document.getElementById('fadebutton'),
    growBtn = document.getElementById('growbutton');

growBtn.addEventListener('click', function() {
  let growVariable = 10,
      boxHeight = parseInt(box.style.height),
      boxWidth = parseInt(box.style.width);

  box.style.height = boxHeight + growVariable + "px",
  box.style.width = boxWidth + growVariable + "px";
  
});

fadeBtn.addEventListener("click", function() {
  let opVariable = .2,
      opValue = parseFloat(box.style.opacity) || 1;
  
  box.style.opacity = opValue - opVariable;
  
});
<div id="box" style="height: 100px; max-height: 600px; min-height: 5px; width:100px; max-width: 600px; min-width: 5px; background-color:orange; margin:1rem"></div>
<button id="fadebutton">Fade</button>
<button id="growbutton">Grow</button>


推荐阅读