Summarize and share several methods to better control timers with the help of CSS

青灯夜游
Release: 2022-09-16 20:22:11
forward
2578 people have browsed it

Summarize and share several methods to better control timers with the help of CSS

Timers are used in many situations in daily work, such as delayed loading, scheduled queries, etc., but sometimes the control of timers can be a little troublesome, such as when the mouse is moved to stop, Remove and start again. This time I will introduce a few methods to better control the timer with the help of CSS. Let’s learn about it together. I believe it can bring a different experience. [Recommended learning: css video tutorial]

1. Hover delay trigger

There is such a scene, when the mouse stays on an element The event will be triggered after 1s, and it will not be triggered if it is not satisfied with 1s. The advantage of this is that it can avoid frequent triggering of events when the mouse moves quickly. If it is implemented with js, it may be like this

var timer = null
el.addEventListener('mouseover', () => {
  timer && clearTimeout(timer)
  timer = setTimeout(() => {
    // 具体逻辑
  }, 1000)
})
Copy after login

Isn’t this the case? Wait, this is not over yet. This only achieves a delay. It will still trigger after the mouse leaves. You also need to cancel the timer when the mouse leaves.

el.addEventListener('mouseout', () => {
  timer && clearTimeout(timer)
})
Copy after login

In addition, is using mouseoutYou also need to consider the dom nested structure, because these events will still be triggered during the parent-> child process. In short, there will be a lot of details, It's easy to trigger by mistake.

Now comes the turning point. If you borrow CSS, you can effectively avoid the above problems. As follows, first add a delayed transition

button:hover{
  opacity: 0.999; /*无关紧要的样式*/
  transition: 0s 1s opacity; /*延时 1s */
}
Copy after login

to the element that needs to be triggered. Just one irrelevant style is enough here. If opacity has already been used, you can use other ones, such as transform:translateZ(.1px), which is also feasible. Then add the listener transitionendmethod

GlobalEventHandlers.ontransitionend - Web API Interface Reference | MDN (mozilla.org)

el.addEventListener('transitionend', () => {
  // 具体逻辑
})
Copy after login
Copy after login

This is the end. No timer, no cancellation, no need to consider the dom structure, perfect implementation.

The following is a small example, triggered after hover for a period of timealert

Summarize and share several methods to better control timers with the help of CSS

The principle is consistent with the above , the complete code can be viewed online demo: hover_alert (codepen.io) or hover_alert(runjs.work)

? Will you encounter this again in the future? If you need to, you can stop and think about it. Many interactions related to mouseover can be implemented in this way.

2. Long press trigger event

Long press Pressing is also a relatively common requirement. It can be well distinguished from click events, thereby giving more interactive capabilities.

But there is no such event in native js. If you want to implement a long press event, you usually need to use a timer and mouse press event, as follows

el.onmousedown = function(){
    this.timer && clearTimeout(this.timer);
    this.timer = settimeout(function(){
        //业务代码
    },1000)
}
el.onmouseup = function(){
    this.timer && clearTimeout(this.timer);
}
Copy after login

again The scenario of timer and timer cancellation is somewhat similar to the previous example. It can also be implemented with the help of CSS. Since the mouse is pressed, it can be associated with :active, so it can be implemented like this

button:hover:active{
  opacity: .999; /*无关紧要的样式*/
  transition: opacity 1s; /*延时 1s */
}
Copy after login

Then listen againtransitionendmethod

el.addEventListener('transitionend', () => {
  // 具体逻辑
})
Copy after login
Copy after login

Isn’t it very convenient? The following is a small case that I have done before, which implements long-press trigger element selection

2 (1).gif

The complete code can be viewed online demo: Long-press box selection (codepen. io)orLong press the box to select (runjs.work)

3. Carousel and pause

Let’s look at a more interesting example, the carousel image .

Usually the carousel image will play automatically, and then the carousel image will be paused when the mouse hover is used. The usual approach is like this

function autoPlay(){
  timer && clearInterval(timer)
  timer = setInterval(function(){
    // 轮播逻辑
  }, 1000)
}
autoPlay()
view.onmouseover = function(){
    timer && clearInterval(timer)
}
el.onmouseout = function(){
    autoPlay()
}
Copy after login

It is also the timer cancellation and Settings requires binding a bunch of events, which is too annoying. Can I try another method? Of course, with CSS animations, it’s all easy.

is not the same as before, here is setInterval, which can be triggered repeatedly. So what is there in CSS that can be triggered repeatedly? That's right, it's CSS animation! When the CSS animation is set to infinite, it can loop infinitely. The effect is very similar to this timer, and the animation can be paused and played directly through :hover. To monitor the triggering of each animation, you can use the animationiteration method, which means that each animation cycle is triggered once

GlobalEventHandlers.onanimationiteration - Web API 接口参考 | MDN (mozilla.org)

所以用这种思路实现就是

.view {
  animation: scroll 1s infinite; /*每1s动画,无限循环*/
}
.view:hover{
  animation-play-state: paused; /*hover暂停*/
}
@keyframes scroll {
  to {
    transform: translateZ(.1px); /*无关紧要的样式*/
  }
}
Copy after login

然后再监听animationiteration事件

view.addEventListener("animationiteration", () => {
  // 轮播逻辑
})
Copy after login

是不是省去了大半的js代码?而且也更好理解,控制也更为方便。

下面是一个通过animationiteration来代替setInterval实现的轮播图

Summarize and share several methods to better control timers with the help of CSS

完整代码可以查看线上demo:CSS banner(codepen.io)或者css_banner(runjs.work)

四、总结一下

以上就是你可能不需要定时器的几个替代方案,相比定时器而言,CSS 在控制定时器的开启和暂停上更有优势,下面总结一下

  • :hover配合transition延时、transitionend监听可以实现鼠标经过延时触发效果

  • :active配合transition延时、transitionend监听可以实现长按触发效果

  • CSS 动画设置infinite后配合animationiteration监听可以实现周期性触发效果

  • 可以直接通过:hover来控制台动画的暂停和播放

当然,可以利用的不仅仅是以上几个案例,任何和 CSS 交互(:hover:active)有类似功能的都可以朝这个方向去思考,是不是可以实现地更加优雅?

(学习视频分享:web前端

The above is the detailed content of Summarize and share several methods to better control timers with the help of CSS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
css
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template