简体   繁体   English

CSS hover效果和Javascript onMouseOver事件

[英]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:在工作中处理项目时,我被告知在 CSS class 而不是 JS function 中实现以下 JS 代码:

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?简而言之:为什么我不应该在 React 中创建 mouseOver class 而是使用 CSS class? Does it take long time to implement JS function over CSS hover? JS function 比 CSS hover 执行时间长吗?

The reason why CSS is preferred over JS wherever the trade can be offered is simple.在可以提供交易的地方,CSS 优于 JS 的原因很简单。

  1. CSS works on the fly and is 10x faster than Javascript. CSS 在运行中工作,比 Javascript 快 10 倍。
  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.与 CSS 相比, :hover是默认的 HTML 属性,可以使用 CSS 进行自定义。

tl;dr tl;博士

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. CSS :hover:focus和所有其他此类选择器会修改默认的 HTML 行为,而 Javascript 事件侦听器会向现有的 HTML 节点添加附加功能。 The trade-off is tremendous as soon as scalability is the subject.一旦可扩展性成为主题,权衡是巨大的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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