简体   繁体   中英

How can I make text change color after button click and change back the color after a couple of seconds of no clicking?

I want some text to go red when a button is clicked. The button can be clicked many times and will make the text stay red. After a bit of not clicking the button, the text should go back to black.

Here is a JSFiddle of what I tried: 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)
}

I can't use a setTimeout because then there would be many setTimeout calls in the stack thus messing up what I am trying to achieve.

I know I can probably hardcode a solution by using a variable to check if it has been clicked along with some other checks to check when it was last clicked but I think there is a better solution out there.

Just changed to toggle and added a bit more time. Seems to work now.

Added a flag to prevent multi clicks.

 // 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,因为它以毫秒为单位

This might do it for you. A simple adjustment by checking if its active or not

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM