我想点击一个按钮,当一些文字去红色。该按钮可以点击多次,将会使文本保持为红色。有点不点击该按钮后,该文本应该回到黑色。
下面是我试过的jsfiddle:https://jsfiddle.net/9tdschym/1/
<p class="text">Text</p>
<button>Click</button>
.clicked {
color: red;
}
let text = document.querySelector( '.text' )
let btn = document.querySelector( 'button' )
btn.onclick = () => {
text.classList.add( 'clicked' )
setTimeout(() => {
text.classList.remove( 'clicked' )
}, 500)
}
我不能使用setTimeout的,因为那时会有堆栈中的许多setTimeout的呼叫从而搞乱了什么,我想要的目的。
我知道我可以用一个变量来检查是否已被点击它连同其他一些检查,以检查它什么时候被点击的可能是硬编码解决方案,但我认为这是一个更好的解决方案在那里。
只是改变了切换和更增添了几分的时间。似乎现在的工作。
增加了一个标志,以防止多的点击。
// Text will change for (n) milliseconds on click.
// Further clicks will reset timeout
let text = document.querySelector( '.text' )
let btn = document.querySelector( 'button' )
let timer = undefined;
btn.onclick = () => {
if(timer !== undefined) {
clearTimeout(timer);
} else {
text.classList.toggle( 'clicked' )
}
timer = setTimeout(() => {
text.classList.toggle( 'clicked' );
timer = undefined;
}, 1500)
}
.clicked {
color: red;
}
<p class="text">Text</p>
<button>Click</button>
它的实际工作,但你需要输入5000,因为这个作品以毫秒为单位
这可能会为你做它。一个简单的调整通过检查它的活性或不
let text = document.querySelector( '.text' )
let btn = document.querySelector( 'button' )
let active = false
btn.onclick = () => {
if(!active){
text.classList.add( 'clicked' )
active = true;
setTimeout(() => {
text.classList.remove( 'clicked' )
active = false;
}, 1500)
}
}
.clicked {
color: red;
}
<p class="text">Text</p>
<button>Click</button>