With CSS to manage js events

CSS is an amazing language, and many of its functions irrelevant able to play a very significant effect, some appear to have achieved a certain amount of work in js, CSS a property can be easy to solve, let's look A few examples (mainly related events and js).

Many of which are open brain hole to come out, to achieve the effect is amazing accident

Original issues

github.com/XboxYan/not…

Events are disabled

Js disabled in the event is not complicated, but it is easy to affect the business logic

function buy(){
  if(XX){
    return false;
  }
  //其他业务代码
}
复制代码

Of course, the elements have to set the appropriate style, it looks not clickable.

css disabled events is relatively simple, there are two main ways

1. disabled

Native form elements are disabled by default of the property, such as

<button disabled onclick="alert(11)">按钮</button>
复制代码

As can be seen, the default style for the disabled

button:disabled {
    color: graytext;
}
复制代码

So, here you are free to modify the style of disabled

button:disabled {
    color: red;
}
button[disabled] {/**属性选择器也行**/
    color: red;
}
button:hover { /**:hover支持**/
    color: red;
}
button:active,button:focus{/**不支持,其实也好理解,会触发focus()事件,所以也禁用了**/
  color:red
}
复制代码

Under normal circumstances, the use of this approach is relatively good, natural disabled properties, compatibility is not bad

2. pointer-events:none

This property should not be unfamiliar, the most common usage is to disable a button, but not limited to the form element, any element can be (for example, many people like to use a label)

button.disabled {
    pointer-events:none;
    user-select:none;/*去除选中效果*/
    color: graytext;
}
复制代码

This property is useful for many, many js brains want to filter out the way to solve directly with the property line here is not started, a lot of online tutorials.

View the demo

See the Pen css 禁用事件 by XboxYan ( @xboxyan) on CodePen.

Press events

Native js and did not press event, usually developers will generally follow the ideas, using the timer to complete

The following is a pseudocode

el.onmousedown = function(){
    this.timer && clearTimeout(this.timer);
    this.timer = settimeout(function(){
        //业务代码
    },350)
}
el.onmouseup = function(){
    this.timer && clearTimeout(this.timer);
}
复制代码

Of course, you can use css to complete, and better, easy to control

Why here said to be "with the" it, because we can not fully css to complete, just use some of the features

css3 transitions and animations in a new property, with the corresponding callback event also presupposes these animations, as follows

event Explanation
transitionstart Triggered at the start of transition
transitionrun When triggered during transition
transitioncancel Fires when the transition canceled
transitionend Upon completion of the transition trigger
animationstart Triggered when the animation start
animationiteration Fired when the animation to complete a cycle
animationend Fired when the animation is completed
animationcancel Fires when animation canceled

Compatibility issues some events, are interested can study in detail

With these events, do a long press event is very easy, here are two all sorts of ideas, we can look at the brain-dong

Suppose you want to delay 1s;

  1. The transition time is set to 1s, call transitionendoranimationend
  2. Delay 1s, call transitionstartoranimationstart

Here in the first case transitionend(the transition is much easier to achieve than the movie, the code less, preferentially with a transition) to achieve

button:hover:active{
  opacity:.99;/**随便选取一个不影响页面的可以过渡的样式**/
  transition:opacity 1s;
}
复制代码

Appropriate, js need to listen to transitionendthe event, without the aid of a timer (personal little contempt thought timer ^)

el.addEventListener('transitionend',function(){
    //业务代码
})
复制代码

A lot of it is not streamlined, need to change a long time can be controlled directly by css

Here a little package custom events, can be better used in the project (though the code itself is very small).

View the demo

See the Pen css 长按事件 by XboxYan ( @xboxyan) on CodePen.

Single-click event

In the jquerymiddle there is a once(like this) method, bindings represent a one-time event, click once after no longer effective.

Native js achieve this is not complicated, the usual practice is to define a logo, a change after clicking the following pseudo-code

el.onclick = function(){
   if(!this.once){
       //业务代码
       this.once = true;
   }
}
复制代码

With the above ideas, css can also achieve a similar effect, get to the bottom of something, summarize the following two methods

1.animationend

animationendAfter the animation is triggered, it is clear that we can make a fuss here

For example, we can give a suspended state in the initial state animation-play-state:paused, then the motion when clicked animation-play-state:running, after the state has remained at lastanimation-fill-mode: forwards

.button{
  animation: once .01s paused forwards;/**给一个足够小的运动时间,确保能够在`:active`时运动完成**/
}
.button:hover:active{
  animation-play-state:running;
}
@keyframes once {
  to{
    opacity:.8;
  }
}
复制代码

js only need to animationendlisten

el.addEventListener('animationend',function(){
    //业务代码
})
复制代码

2. achieve pure css

I do not know if I have found in the above example, at the end of the animation elements disabled happen?

@keyframes once {
  to{
    opacity:.8;
    pointer-events:none;
    user-select:none;
  }
}
复制代码
<button class="button" onclick="fn()">按钮</button>
复制代码

This can disable the movement finished, it seems to be perfect?

In fact, here it is difficult to control the movement of time, as we all know, onclickin fact, contains the press and lift the two processes, if the lift is too slow, then the time element has been disabled, can not trigger event; if the lift Since too fast, if quick click, not because the movement is completed, it will trigger multiple events.

Solution is also very simple to use onmousedowninstead of to

<button class="button" onmousedown="fn()">按钮</button>
复制代码

View the demo

At The Pen See CSS single event by XboxYan ( @xboxyan ) ON CodePen .

onresize event

We all know that windowthere is onresizean event can be triggered when the window stretching, then you can get real-time window size, and so on property.

window.onresize = function(ev){
   //业务代码
}
复制代码

However, common elements but not this listener, such as

div.onresize = function(ev){
   //不生效...
}
复制代码

Why do we need this function?

As you may know there is such a property, you can stretch the native elements, change the size

.box{
    overflow: hidden;/**需要配合overflow才能生效**/
    resize: both;
}
复制代码

Only one attribute, a tensile element can be achieved (although slight flaws), does not require much js calculated.

Fortunately, visual display, but if you need to know how to do real-size elements of it, js are usually two ideas

1. onmousemove event

Stretch of time is very natural to think there is a hold down and drag the mouse to complete, so you can add elements to onmouse-*a series of events, keeping in mind the mouse lifted listen to cancel

//大概是这样的逻辑
div.onmousedown = function(){
    div.onmousemove = fn;//监听
    div.onmouseup = function(){
        div.onmousemove = null;
    }
}
复制代码

2. Timer

With setIntervalor requestAnimFrameto achieve monitoring, also need to pay attention to listen to cancel the timing

//大概是这样的逻辑
div.onmousedown = function(){
    this.timer && clearInterval(this.timer)
    this.timer = setInterval(fn,300);//监听
    div.onmouseup = function(){
        this.timer && clearInterval(this.timer)
    }
}
复制代码

Obviously, the above methods are not particularly comfortable, problems will arise listening canceled in many cases, lead to non-stop trigger, impact experience.

At this time, it is the turn played css, js I think a lot of time to implement is not smooth at all times can be recognized again by thinking of css.

So, how to use css to listen to this?

It can be considered from two ideas transitions and animations.

1. CSS transition

First, we can know is that by resize: boththe time stretching elemental change that widthand height, as can be seen directly from the developer tools

We need to pass transitionrunor transitionendto listen widthand height, so it is necessary to add these two properties transition

.box{
   transition:width .3s,ehight .3s;//分别给width和height设置过渡,其他属性不需要
}
复制代码

So that you can get a monitor, but this approach has a drawback, because the transition will take time, so there is a not to follow the feeling of Caton.

So we look at the second way

2. animationiteration

cssYou can set the animation plays, if set animation-iteration-count: infiniteto represent an infinite carousel, with animationiterationcallbacks can be achieved not listen yet

.box:active{
    animation: resize .3s infinite forwards;
}

@keyframes resize{
    to {
       opacity: .99;/**用一个无关紧要的属性来触发动画**/
    }
}
复制代码

js is very simple, a listener will be able to solve the problem, nor what needs to listen to cancel anything, these have been done in css

el.addEventListener('animationiteration',function(){
    //业务代码
})
复制代码

Here is the complete animation once each callback once, so we can grow to control the frequency of the monitor by setting animation, such as the above is .3sthe trigger frequency.

Here wrote a demo, you can implement custom onresizeevent

View the demo

See the Pen css resize事件 by XboxYan ( @xboxyan) on CodePen.

Section

By means of the above css, js achieve a number of very difficult issues, there may be more application scenarios, welcomed the junior partner message discussion ~

Guess you like

Origin blog.csdn.net/weixin_34037173/article/details/91362222