javascript - 每次单击淡入淡出按钮都会使背景框不断淡入淡出
问题描述
全新的编码。每次单击时,都试图让“淡入淡出”按钮淡出一点。我已经使用此代码来扩大和缩小盒子,并且我试图对不透明度做同样的事情:
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 吗?
解决方案
您现有的代码会产生错误:Uncaught ReferenceError: newValueHeight is not defined
. 有几个问题:
- 您是在引用
newValueHeight
而不是newOpValue
偶然。 parseInt()
将返回一个整数,即如果当前不透明度为 0.8,则parseInt(0.8)
返回1
. 您需要使用parseFloat()
来获取浮点数。- 最初,
style.opacity
是undefined
因为它尚未设置。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>
推荐阅读
- spring - 如何从构建路径中删除休眠核心 jar
- javascript - “index.js?v=xxx”是干什么用的?
- r - 在 R 中将热图刻度从数字更改为月份
- java - 既然抽象类可以有公共构造函数,为什么不能实例化呢?
- python - Django TypeError:__init__() 接受 1 个位置参数,但给出了 2 个
- mysql - 这个 SQL 谜题中的两个破折号是干什么用的?
- javascript - 需要帮助使用另一个 JS 将代码添加到 JS
- reactjs - 获取 Firebase:没有创建 Firebase 应用“[DEFAULT]”错误
- flutter - 全宽与列子不工作
- reactjs - React Redux + Infinite Scroll = 重新渲染整个列表?