Home>Article>Web Front-end> 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]
There is such a scene, when the mouse stays on an elementThe event will be triggered after 1s
, and it will not be triggered if it is not satisfied with1s
. The advantage of this is that it can avoid frequent triggering of events when the mouse moves quickly. If it is implemented withjs
, it may be like this
var timer = null el.addEventListener('mouseover', () => { timer && clearTimeout(timer) timer = setTimeout(() => { // 具体逻辑 }, 1000) })
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) })
In addition,is usingmouseout
You also need to consider thedom
nested structure, because these events will still be triggered during theparent-> 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 delayedtransition
button:hover{ opacity: 0.999; /*无关紧要的样式*/ transition: 0s 1s opacity; /*延时 1s */ }
to the element that needs to be triggered. Just one irrelevant style is enough here. Ifopacity
has already been used, you can use other ones, such astransform:translateZ(.1px)
, which is also feasible. Then add the listenertransitionend
method
GlobalEventHandlers.ontransitionend - Web API Interface Reference | MDN (mozilla.org)
el.addEventListener('transitionend', () => { // 具体逻辑 })
This is the end. No timer, no cancellation, no need to consider thedom
structure, perfect implementation.
The following is a small example, triggered afterhover
for a period of timealert
The principle is consistent with the above , the complete code can be viewed online demo:hover_alert (codepen.io)orhover_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.
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 nativejs
. 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); }
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 */ }
Then listen againtransitionend
method
el.addEventListener('transitionend', () => { // 具体逻辑 })
Isn’t it very convenient? The following is a small case that I have done before, which implements long-press trigger element selection
The complete code can be viewed online demo:Long-press box selection (codepen. io)orLong press the box to select (runjs.work)
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 mousehover
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() }
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 issetInterval
, which can be triggered repeatedly. So what is there in CSS that can be triggered repeatedly? That's right, it'sCSS animation! When the CSS animation is set toinfinite
, 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 theanimationiteration
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); /*无关紧要的样式*/ } }
然后再监听animationiteration
事件
view.addEventListener("animationiteration", () => { // 轮播逻辑 })
是不是省去了大半的js
代码?而且也更好理解,控制也更为方便。
下面是一个通过animationiteration
来代替setInterval
实现的轮播图
完整代码可以查看线上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!