简体   繁体   中英

How to toggle text decorations

How do I toggle the line-through ( textDecoration ) on the list below when clicked?

 const items = document.querySelectorAll('li'); items.forEach(item => { item.addEventListener('click', (e) => { e.target.style.textDecoration.toggle('line-through'); }) })
 <ul> <li>buy milk</li> <li>read a book</li> <li>play the guitar</li> <li>pay the bills:(</li> </ul>

This doesn't work, but

e.target.style.textDecoration = 'line-through'

adds the line-through where I want it, I just don't know how I can do this using the toggle function? I know I could this with If Else statements.

You can toggle based on the current value of that style property.

 const items = document.querySelectorAll('li'); items.forEach(item => { item.addEventListener('click', (e) => { item.style.textDecoration = item.style.textDecoration === 'line-through'? '': 'line-through'; }) })
 <ul> <li>buy milk</li> <li>read a book</li> <li>play the guitar</li> <li>pay the bills:(</li> </ul>

Alternatively, toggle a class.

 const items = document.querySelectorAll('li'); items.forEach(item => { item.addEventListener('click', (e) => { item.classList.toggle('line-through'); }) })
 .line-through { text-decoration: line-through; }
 <ul> <li>buy milk</li> <li>read a book</li> <li>play the guitar</li> <li>pay the bills:(</li> </ul>

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