简体   繁体   中英

CSS hover effect and Javascript onMouseOver event

While working on the project at work, I was told to implement below JS code in CSS class rather than JS function:

function onMouseOver(e : any) {
     e.target.style.textDecoration = 'underline';
}

function onMouseLeave(e : any) {
    e.target.style.textDecoration = 'none';
}

What is the trade-off between two of them and why one of them should be preferred over another.

Short: why shouldn't I create mouseOver class in React but use CSS class? Does it take long time to implement JS function over CSS hover?

The reason why CSS is preferred over JS wherever the trade can be offered is simple.

  1. CSS works on the fly and is 10x faster than Javascript.
  2. Event listeners are functions, functions that are called every single time the event is performed. Compare that to what CSS does, :hover is a default HTML property that can be customized using CSS.

tl;dr

CSS :hover , :focus , and all the other such selectors modify the default HTML behaviour, whereas Javascript event listeners add additional functionality to existing HTML nodes. The trade-off is tremendous as soon as scalability is the subject.

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