[Web API] PC side web effects

▊ element offset offset

Use offset to dynamically get the position (offset), size, etc. of the element

Note: offset refers to the parent element with positioning; size refers to the width and height of its entire box; the return value does not have unit

box.offsetTop			// Up offset
box.offsetLeft			// Left offset position
box.offsetWidth			// wide
box.offsetHeight		// high
box.offsetParent		// Return to father with location

offsetWidth and style.width Difference in height

  1. offset can get the style value of any style sheet; style.width You can only get the style values in the row style sheet (not in-line css!!!)
  2. offset returns a number without a unit; style.width String with units returned
  3. Offset width is the whole box (width+padding+border); style.width You get width
  4. offsetWidth is read-only and cannot be modified by assignment; style.width Readable and writable
  5. Therefore: offsetWidth is suitable for obtaining the location and size of elements; style.width Suitable for modification of elements

▊ element visible area client

Use client to dynamically get the border size and element size of the element

box.clientTop				// Size of top border (rarely used)
box.clientLeft				// Size of left border
box.clientWidth				// Return width (including padding and its own width, excluding border)
box.clientHeight			// Return width (including padding and its height, excluding border)

▊ element scroll scroll scroll

Use scroll to dynamically get the size and rolling distance of elements

box.scrollTop				// The distance above the volume
box.scrollLeft				// Distance to the left of the coil
box.scrollWidth				// Return width (including padding, excluding border)
box.scrollHeight			// Return height (including padding, excluding border)

// The difference with clientWidth and clientheight is the actual width and height of the returned content, including the excess part

// Pay attention to distinction - the head of the page being rolled is pageYOffset; the head of the box being rolled is scrollTop (the same width)

▊ summary of three series

In terms of getting element size: offset gets the one with border; client and scroll do not contain border; both contain padding; scroll also contains excess content

Main usage: offsetTop and offsetLeft are used to get position offset; offsetWidth and offsetHeight(clientWidth and clientHeight) are used to get element size; scrollTop and scrollLeft are used to get scrolling distance; page scrolling distance is used window.pageXOffset , window.pageYOffset ; almost none of the others

The main use above is the key!

▊ supplementary content -- execute function immediately

// No need to call, execute immediately
// Style:
(function() {})()			// In fact, this is the easiest to understand (in fact, parameters are passed in immediately after declaration >_ <)
(function() {}())			// Of course it can

(function(a, b) {
    console.log(a + b);
})(2, 3);						// Output 5
(function(a, b) {
    console.log(a + b);
}(2, 3));						// Output 5

// ☀  Main purpose: each immediate function creates a separate scope, which avoids naming conflicts

▊ supplementary content -- the difference between mouseover and mouseenter

mouseover will be triggered after passing through its own box, and it will also be triggered after passing through its own box; mouseenter will only be triggered after passing through its own box

mouseover is triggered by its own box, which is actually the result of bubbling of the sub box;

That is to say, mouseover does not bubble, mouseenter does not bubble (mouseleave also does not bubble)

▊ animation function encapsulation

The core principle of animation implementation is to constantly move the box position through the timer setInterval()

// Encapsulation of simple animation function: parameters include target object obj, target location target
function anime(obj, target) {
    clearInterval(obj.timer); 					// Clear previous timers to prevent elements from having multiple timers
    obj.timer = setInterval(function() { 		// Different timers are pointed to different objects (saving resources and avoiding naming ambiguity)
        if (obj.offsetLeft >= target) {
        } else {
            obj.style.left = obj.offsetLeft + 1 + 'px';
    }, 30);

// Optimization: slow down (by modifying step size) + returnable (reverse by negative value of step size)
function anime(obj, target) {
    obj.timer = setInterval(function() { 
        var step = (target - obj.offsetLeft) / 10; 					// By setting the variable step size, the effect of slowing down is realized ingeniously
        step = step > 0 ? Math.ceil(step) : Math.floor(step); 		// Avoid the bug that cannot reach the specified location after getting to 0 (key and difficult points)
        if (obj.offsetLeft == target) {
        } else {
            obj.style.left = obj.offsetLeft + step + 'px';
    }, 30);

// Add function again: add callback function
// In fact, it's very simple to declare animation functions, and then pass in a function argument (anonymous function or function name):
function anime(obj, target, callback){
	if(callback){						// Don't forget that JS allows any number of arguments to be passed in, that is, it has its own overload (we can use callback functions)
		callback();						// Usually this sentence is written after clearinterval (timer) - call this effect at the end of the animation
	// A more elegant way of writing
	callback && callback();

Although the animation function encapsulated above is not css silky, it is definitely more classic and powerful than you think

In the following cases of PC side web effects, they will be frequently used and have excellent results


----------------------------------------------------------Dividing line----------------------------------------------------------------
▊ special effects case of PC side web page

❶ get the mouse click position

var box = document.querySelector('.box');
box.addEventListener('click', function(e) {
	// Clever use of a subtraction (itself not difficult, but need to think of!!!)
	var dx = e.pageX - this.offsetLeft;	
	var dy = e.pageY - this.offsetTop;


❷ drag box

// Core idea: it is divided into three steps: mouse press - mouse move - mouse bounce
// In addition to mouse button binding on the box, the other two events are bound on the document!

var box = document.querySelector('.box');
box.addEventListener('mousedown', function(e) {
    var dx = e.pageX - box.offsetLeft; 							// Press the mouse to get the position of the mouse relative to the box (this position is invariant when dragging)
    var dy = e.pageY - box.offsetTop;
    // Mouse movement and mouse bounce events, must be located in the mouse down!!!
    document.addEventListener('mousemove', move); 				// Move the mouse, and assign the left and top of the box by calculating (the position of the mouse on the page - the position of the mouse relative to the box)
    document.addEventListener('mouseup', function() { 			// Mouse up, remove mouse move event
            document.removeEventListener('mousemove', move);
    function move(e) { 		// Calculation of box position when mouse moves
        box.style.left = e.pageX - dx + 'px';
        box.style.top = e.pageY - dy + 'px';


Taobao sidebar case

// The requirement is: the sidebar originally scrolls with the main body and is fixed at some point

// The key point is to get the curled value at the top of the page. When the value reaches a certain value, change absolute positioning to fixed positioning
// Review what is absolute positioning again: it is not to say that it is always fixed somewhere on the page (that is fixed positioning), it will also scroll with the page scrolling, and do not misinterpret the word "absolute"

var bar = document.querySelector('.bar');
document.addEventListener('scroll', function() { 	// When scrolling events, the document scrolls. The event source is document
    if (window.pageYOffset >= 300) {				// pageYOffset is the header of the page being rolled out; scrollTop is the header of the box being rolled out; pay attention to the distinction
        bar.style.position = 'fixed';
    } else {
        bar.style.position = 'absolute';

// In fact, there is a little bug. When changing to fixed location, fixed location should be set at the same time. This can be realized through simple calculation using offsetTop


❹❹ navigation bar effect (sliding and fixing of the selected area)

// html and css are very simple, UL > Li * 6 and have an absolute positioning. cloud; they belong to the. Box big box

// Core idea:
// After. box relative positioning, use offsetLeft as the target location of cloud movement
// The anime displacement animation function encapsulated above is of great use

window.addEventListener('load', function() {
    var box = document.querySelector('.box');
    var cloud = document.querySelector('.cloud');
    var lists = document.querySelectorAll('li');
    var current = 0; 		// current as starting position
    for (var i = 0; i < lists.length; i++) {
        lists[i].addEventListener('mouseenter', function() {
            anime(cloud, this.offsetLeft);				 // Move cloud after mouse
        lists[i].addEventListener('mouseleave', function() {
            anime(cloud, current); 						// Mouse away, cloud back to the starting position
        lists[i].addEventListener('click', function() {
            current = this.offsetLeft; 					// Click the mouse to update the cloud starting position to here


















☀ Loli & JS

♫ Suki

Posted on Sat, 13 Jun 2020 21:42:48 -0400 by diesel