我想使用本机DOM而不是JQuery来实现fadeIn和fadeOut。
如果我们快速单击按钮两次,则意味着当fadeIn仍在进行时它将开始fadeOut,文本将闪烁。
这是jsfiddle中的代码:https://jsfiddle.net/keegoo/vyuqdxLs/
关于如何解决此问题的任何想法?
document.getElementById('button').addEventListener('click', () => switch_state())
const text = document.getElementById('text')
const btn = document.getElementById('button')
let state = true
function switch_state() {
if (state == true) {
fadeOut(text, 3000)
btn.innerHTML = 'show'
state = false
} else {
fadeIn(text, 3000)
state = true
btn.innerHTML = 'hide'
}
}
function fadeOut(elem, ms) {
elem.style.opacity = 1
if (ms) {
let opacity = 1
const timer = setInterval(() => {
opacity -= 50 / ms
if (opacity <= 0) {
clearInterval(timer)
opacity = 0
}
elem.style.opacity = opacity
}, 50)
} else {
elem.style.opacity = 0
}
}
function fadeIn(elem, ms) {
elem.style.opacity = 0;
if (ms) {
let opacity = 0;
const timer = setInterval(function() {
opacity += 50 / ms;
if (opacity >= 1) {
clearInterval(timer);
opacity = 1;
}
elem.style.opacity = opacity;
}, 50);
} else {
elem.style.opacity = 1;
}
}
<button id='button'>hide</button>
<text id='text'>some text</text>
您可以用setProperty
这样操作。
document.getElementById('button').addEventListener('click', () => switch_state())
const text = document.getElementById('text')
const btn = document.getElementById('button')
let state = true
function switch_state() {
if (state == true) {
fadeOut(text, 800)
btn.innerHTML = 'show'
state = false
} else {
fadeIn(text, 800)
state = true
btn.innerHTML = 'hide'
}
}
function fadeOut(elem, ms) {
elem.style.setProperty("opacity",0);
elem.style.setProperty("transition", ms + "ms");
}
function fadeIn(elem, ms) {
elem.style.setProperty("opacity",1);
elem.style.setProperty("transition", ms + "ms");
}
<button id='button'>hide</button>
<text id='text'>some text</text>