This is the seventh day of my participation in the First Challenge 2022

preface

Hello everyone, I do not eat fish d cat, today is New Year’s Eve, ha ha ha, we still need to update the article, the front to you write a lot of projects, some simple CSS is not to write, some effects. When we are browsing the web, do we often see the effect of button clicking? Today I’m going to use the js event to make a button click effect for you.

Mouse down and up events

The premise

As we all know, JS is an event-driven language. There are many event types, such as mouse events, keyboard events, form events, other events, etc. When we click the button, it must trigger the click event, but in the click event there are click event, double click event, left and right middle key event, as well as press and lift event, we must have encountered when browsing the web page, such as click OK ah, right click display menu ah and so on are common. Today we talk about

  • Press:mousedown
  • Lift:mouseup

It’s semantic and easy to understand

Click on the effect of

rendering

Code implementation

positioning

Before implementation we review relative and absolute localization \

  • Relative positioning:position: relative;

Elements are still placeholders relative to themselves, do not leave the document flow, and move relative to themselves.

  • Absolute positioning:position: absolute;

After absolute positioning, the element does not occupy the location and is completely removed from the document stream. Note: first look for the nearest ancestor element that has the location attribute. If not, look for the browser.

implementation

When we click, the button moves up and down, so we set the button to rise a few pixels when the mouse is pressed, that is, we can change the top property of the button, and when the mouse is lifted, the mouse returns to its original position. That is to change the position of the button. \

structure

  <div>
        <p>Clicking on me has an effect</p>
    </div>
Copy the code

The script tag

Get the object first in JS

// Get the object
let op = document.querySelector('p')
Copy the code

Press the mouse button to change the properties of the button.

 op.onmousedown = () = > {
            op.style.cssText = 'top:8px'
        }
Copy the code

The mouse raises the event to change the properties of the button

 op.onmouseup = () = > {
            op.style.cssText = 'top:12px'
        }
Copy the code

add

Cursor: pointer; , I like to use, after all, is to increase user experience. I’m going to talk to you about how it works, but it’s the same idea that’s used in a lot of places. For example, in e-commerce sites, the effect of commodity browsing is not such an idea, how to say, are to increase the user experience.