Web API learning notes day05, 06, 07

Keywords: Javascript Front-end

1.offset series

  • Offset, offset, can only be obtained and cannot be changed
  1. offsetTop: returns the offset (Y-axis size) of the element above the parent element with positioning. If not, it is the distance to the body
  2. offsetLeft: returns the offset (Y-axis size) of the element from the left border of the positioned parent element. If not, it is the distance to the body
  3. offsetWidth: returns the width of the element itself, including padding, border and content area
  4. offsetHeight: returns the height of the element itself, including padding, border and content area
  5. offsetParent: returns the parent element with positioning. If not, returns body
  6. Imitation Jingdong magnifying glass code
		var box = document.querySelector('.box');
        var mask = document.querySelector('.mask');
        var big = document.querySelector('.big');
        box.addEventListener('mouseover', function () {
            mask.style.display = 'block';
            big.style.display = 'block';
        });
        box.addEventListener('mouseout', function () {
            mask.style.display = 'none';
            big.style.display = 'none';
        });
        box.addEventListener('mousemove', function (e) {
            var x = e.pageX - this.offsetLeft; //Get mouse coordinates
            var y = e.pageY - this.offsetTop;
            var maskX = x - mask.offsetWidth / 2;
            var maskY = y - mask.offsetHeight / 2;
            //Limit the movement range of the occlusion layer to 0 ~ 100100, which is the width of the large box - the width of the occlusion layer
            var maskMax = box.offsetWidth - mask.offsetWidth;
            if (maskX <= 0) {
                maskX = 0;
            } else if (maskX >= maskMax) {
                maskX = maskMax;
            };
            if (maskY <= 0) {
                maskY = 0;
            } else if (maskY >= maskMax) {
                maskY = maskMax;
            };
            //Occlusion layer coordinates follow mouse coordinates
            mask.style.left = maskX + 'px';
            mask.style.top = maskY + 'px';
            //Moving distance of large picture = moving distance of occlusion layer * maximum moving distance of large picture / maximum moving distance of occlusion layer
            var bigImg = document.querySelector('.bigImg');
            var bigMax = bigImg.offsetWidth - big.offsetWidth; //Maximum moving distance of large picture
            var bigX = maskX * bigMax / maskMax;
            var bigY = maskY * bigMax / maskMax;
            bigImg.style.left = -bigX + 'px';
            bigImg.style.top = -bigY + 'px';
        })

2.client series

  1. clientWIdth, which returns the width of the element itself, including content and padding
  2. clientHeight: returns the height of the element itself, including content and padding
  3. clientTop, returns the size of the top border
  4. clientLeft, returns the size of the left border

3.scroll series

  1. scrollWidth, which returns the width of its own actual content, excluding borders
  2. scrollHeight, which returns the height of its actual content without borders
  3. scrollTop, returns the distance of the upper side rolled up
  4. scrollLeft to return the left distance rolled up
  • window.pageYOffset, the distance the page is rolled up
  • Taobao fixed sidebar code
		var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        var bannerTop = banner.offsetTop;
        var sliderbarTop = sliderbar.offsetTop;
        var main = document.querySelector('.main');
        var goback = document.querySelector('.goBack');
        var mainTop = main.offsetTop;
        document.addEventListener('scroll',function(){
            // console.log(window.pageYOffset); The distance from the previous volume where the page is rolled up
            if(window.pageYOffset >= bannerTop){
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sliderbarTop  - bannerTop + 'px';
            }else{
                sliderbar.style.position = 'absolute';
                sliderbar.style.top = sliderbarTop +'px';
            };
            if(window.pageYOffset >= mainTop){
                goback.style.display = 'block';
            }else{
                goback.style.display = 'none';
            };
        });

4. Touch screen events

  1. touchstart, click to start touching
  2. Touch move, click and stroke, and touch continuously
  3. touchend to end the touch
  4. touchcancel to interrupt the touch

5. Touch common objects of events

  • Are pseudo arrays
  1. touches, a list of all fingers being touched
  2. Targettushes, a list of fingers touching the current DOM element, commonly used
  3. changedTouches, a list of finger state changes, from nothing to have or from have to none
  4. Targettushes [0], get the information of the first finger touching the DOM element
  5. When the finger leaves the screen, there are no touches and targetTouches, but there are changedTouches

6.classList

  • Returns the element class name
  1. classList.add(''), add class name
  2. classList.remove(''), delete the class name
  3. classList.toggle(''), switch class names
  4. classList.contains(''), judge whether the class name is included, and return true or false

7. Local storage

  • Local storage characteristics:
    1. The data is stored in the user browser
    2. It is easy to set and read, and even page refresh will not lose data
    3. The capacity is large, with sessionStorage of about 5M and localStorage of about 20M
    4. Only strings can be stored. You can encode the object JSON.stringify() and store it

7.1sessionStorage

  1. The lifecycle is to close the browser window
  2. Data can be shared in the same window (page)
  3. The value stored as a key value pair must be a string

7.2 localstorage local storage

  1. Lifecycles take effect permanently unless manually deleted
  2. Maximum storage 20M
  3. Under the same domain name, data can be shared
  • correlation method
    1. localStorage.setItem(key,value) stores data
    2. Localstore.getitem (key) to get data
    3. localStorage.removeItem(key), delete data
    4. localStorage.clear(), clear data

8. Relevant case codes

  • Animation principle
		//Function encapsulation, obj target object, target target location
        //Assign different timers to different elements
        function animate(obj, target,callback) {
            //When we keep clicking on the button, the element will be faster and faster because too many timers are turned on
            //Solution: first clear the previous timer and only keep the current timer for execution
            clearInterval(obj.timer,);
            obj.timer = setInterval(function () {
                if (obj.offsetLeft >= target) {
                    // obj.style.backgroundColor = 'red';
                    clearInterval(obj.timer);
                    callback && callback();
                };
                obj.style.left = obj.offsetLeft + 4 + 'px';
            }, 50);
        };
        var div = document.querySelector('div');
        var span = document.querySelector('span');
        var btn = document.querySelector('button');
        animate(div, 300,function(){
            div.style.backgroundColor = 'red';
            // alert(123)
        });
        btn.addEventListener('click',function(){
            animate(span, 200);
        })
  • pc side rotation chart
		var box = document.querySelector('.box');
        var left = document.querySelector('.left');
        var right = document.querySelector('.right');
        var ul = box.querySelector('ul');
        var ol = box.querySelector('.pagination');
        var boxWidth = box.offsetWidth;
        //1. Left and right arrows show and hide
        box.addEventListener('mouseover', function () {
            left.style.display = 'block';
            right.style.display = 'block';
            clearInterval(timer);
        });
        box.addEventListener('mouseout', function () {
            left.style.display = 'none';
            right.style.display = 'none';
            autoLun();
        });
        //2. Dynamically generate small circles. The number of small circles is the same as that of the picture
        for (var i = 0; i < ul.children.length; i++) {
            var li = document.createElement('li');
            //Record the index number of the current small circle through the custom attribute
            // li.setAttribute('data-index', i);
            li.index = i;
            ol.appendChild(li);
            //3. The exclusive thought of small circle adds the class name when clicking, and it is added at the same time when the small circle is generated
            li.addEventListener('click', function () {
                for (var j = 0; j < ol.children.length; j++) {
                    ol.children[j].className = '';
                }
                this.className = 'current';
                //4. Click the small circle to move the picture, and the moving is ul
                //ul the distance moved is the index number of the small circle × The width of the picture is negative
                // var index = this.getAttribute('data-index'); // Click a li to get its index number
                var index = this.index;
                num = circle = index;
                animate(ul, -index * boxWidth);
            })
        };
        ol.children[0].className = 'current';
        //5. Clone the first picture and put it at the back. There will be no more small circle
        var first = ul.children[0].cloneNode(true);
        ul.appendChild(first);
        //6. Click the button on the right to scroll one picture
        var num = 0;
        var circle = 0; //Declare a global variable to control the playback of small circles
        //Next
        right.addEventListener('click', function () {
            //If you get to the last one, ul's left will quickly recover to 0
            if (num == ul.children.length - 1) {
                num = 0;
                ul.style.left = 0;
            };
            num++;
            animate(ul, -num * boxWidth);
            //7. Click the button on the right, and the small circle changes with it
            circle++;
            if (circle == ol.children.length) { //If the small circle goes to the last one, it will return to the first one
                circle = 0;
            };
            for (var i = 0; i < ol.children.length; i++) {
                ol.children[i].className = '';
            };
            ol.children[circle].className = 'current';
        });
        //Previous
        left.addEventListener('click', function () {
            //If you get to the last one, ul's left will quickly recover to 0
            if (num == 0) {
                num = ul.children.length - 1;
                ul.style.left = -num * boxWidth + 'px';
            };
            num--;
            animate(ul, -num * boxWidth);
            //7. Click the button on the right, and the small circle changes with it
            circle--;
            if (circle < 0) { //If the small circle goes to the last one, it will return to the first one
                // circle = ol.children.length-1;
                circle = circle < 0 ? ol.children.length - 1 : cirle;
            };
            for (var i = 0; i < ol.children.length; i++) {
                ol.children[i].className = '';
            };
            ol.children[circle].className = 'current';
        });
        var timer = null;
        function autoLun(){
            timer = setInterval(function(){
                right.click();
        },2000);
        }
        autoLun();
  • Rotation diagram of mobile terminal
		var box = document.querySelector('.box');
        var ul = document.querySelector('.box ul');
        var w = box.offsetWidth;
        var ol = document.querySelector('.box ol');
        var index = 0;
        //Automatic rotation
        var timer = setInterval(function () {
            index++;
            var translateX = -index * w;
            ul.style.transition = 'all .3s';
            ul.style.transform = `translateX(${translateX}px)`;
        }, 2000);
        //After the transition is completed, judge and add events to listen to the transition
        ul.addEventListener('transitionend', function () {
            //Seamless rolling
            if (index >= ul.children.length - 2) {
                index = 0;
                ul.style.transition = 'none'; //Remove the transition effect and make ul jump to the target position quickly
                // var translateX = -index * w;
                ul.style.transform = `translateX(0px)`;
            } else if (index < 0) {
                index = ul.children.length - 3;
                ul.style.transition = 'none'; //Remove the transition effect and make ul jump to the target position quickly
                var translateX = -index * w;
                ul.style.transform = `translateX(${translateX}px)`;
            };
            //Small dots follow the change
            ol.querySelector('.current').classList.remove('current');
            ol.children[index].classList.add('current');
        });
        //Finger swipe rotation chart
        var startX = 0;
        var moveX = 0;
        var flag = false;
        ul.addEventListener('touchstart', function (e) {
            startX = e.targetTouches[0].pageX; //Touch the screen to obtain the initial coordinates of the finger
            clearInterval(timer); //Stop the timer when the finger touches
        });
        //Move the finger, calculate the sliding distance of the finger, and move the box
        ul.addEventListener('touchmove', function (e) {
            flag = true;
            moveX = e.targetTouches[0].pageX - startX; //Moving distance
            var translateX = -index * w + moveX;
            ul.style.transition = 'none';
            ul.style.transform = `translateX(${translateX}px)`;
            e.preventDefault();
        });
        //When the finger leaves, judge the previous or next one
        ul.addEventListener('touchend', function (e) {
            if (flag) {
                if (Math.abs(moveX) > 50) {//Judge whether the moving pixel is greater than 50
                    if (moveX > 0) {//
                        index--;
                    } else {
                        index++;
                    }
                    var translateX = -index * w;
                    ul.style.transition = 'all .3s';
                    ul.style.transform = `translateX(${translateX}px)`;
                } else {
                    var translateX = -index * w;
                    ul.style.transition = 'all .3s';
                    ul.style.transform = `translateX(${translateX}px)`;
                };
            }
            clearInterval(timer); //Continue automatic rotation after releasing your finger
            timer = setInterval(function () {
                index++;
                var translateX = -index * w;
                ul.style.transition = 'all .3s';
                ul.style.transform = `translateX(${translateX}px)`;
            }, 2000);
        })
  • Remember user name
		var username = document.querySelector('#username');
        var remember = document.querySelector('#remember');
        if(localStorage.getItem('username')){
            usewername.value = localStorage.getItem('username');
            remember.checked = true;
        };
        remember.addEventListener('change',function(){
            if(this.checked){
                localStorage.setItem('username',username.value);
            }else{
                localStorage.removeItem('username');
            };
        });

Posted by zorgon on Fri, 05 Nov 2021 14:43:09 -0700