*Web APIs 5 Element offset offset·Element visual area client·Element scroll scroll·Animation function package

**1.1. **Element offset offset series

1.1.1 Overview of offset

offset translates as the offset. We can dynamically get the position (offset), size, etc. of the element using the relevant attributes of the offset series.

  1. Get the distance of the element with the position of the positioned parent element

  2. Get the size of the element itself (width and height)

  3. Note: The returned value does not have a unit
    Insert picture description here
    Insert picture description here

1.1.2 The difference between offset and style

offset

  • offset can get the style value in any style sheet

  • The value obtained by the offset series has no unit

  • offsetWidth 包含padding+border+width

  • Attributes such as offsetWidth are read-only attributes, which can only be obtained and cannot be assigned.

  • Therefore, we want to get the size and position of the element, it is more appropriate to use offset

style

  • style can only get the style value in the inline style sheet

  • style.width gets a string with units

  • style.width gets the value without padding and border

  • style.width is a readable and writable attribute, which can be obtained or assigned

  • So, if we want to change the value of the element, we need to change it with style

Because we usually register touch events for elements, we must remember targetTocuhes

1.1.3 Case: Get the coordinates of the mouse in the box

  1. We click inside the box and want to get the distance between the mouse and the left and right of the box.
  2. First get the coordinates of the mouse on the page (e.pageX, e.pageY)
  3. Second, get the distance of the box on the page (box.offsetLeft, box.offsetTop)
  4. Subtract the distance of the box in the page from the coordinates of the mouse from the page to get the coordinates of the mouse in the box
  5. If you want to move the mouse, get the latest coordinates and use the mouse to move
var box = document.querySelector('.box');
box.addEventListener('mousemove', function(e) {
    
    
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
this.innerHTML = 'x坐标是' + x + ' y坐标是' + y;
})

1.1.4 Case: Drag and drop of modal box

The pop-up box is also called a modal box.

​ 1. Click the pop-up layer, a modal box will pop up, and a gray translucent occlusion layer will be displayed.

​ 2. Click the close button to close the modal frame and close the gray translucent occlusion layer at the same time.

​ 3. Place the mouse on the top row of the modal box, you can hold down the mouse and drag the modal box to move in the page.

​ 4. Release the mouse, you can stop dragging the modal box to move

1.1.5. Case study:

  1. Click on the pop-up layer, the modal box and the occlusion layer will be displayed display: block;
  2. Click the close button, the modal box and the occlusion layer will be hidden display:none;
  3. The principle of dragging in the page: the mouse is pressed and moved, and then the mouse is released
  4. The trigger event is that the mouse presses mousedown, the mouse moves mousemove and the mouse releases mouseup
  5. Drag process: During the mouse movement, the latest value is obtained and assigned to the left and top values ​​of the modal box, so that the modal box can follow the mouse away
  6. The source of the event triggered by the mouse press is the top line, that is, the id is title
  7. The coordinates of the mouse minus the coordinates of the mouse in the box is the real position of the modal box.
  8. When the mouse is pressed, we want to get the coordinates of the mouse in the box.
  9. When the mouse moves, let the coordinates of the modal box be set as: mouse coordinates minus the box coordinates. Note that the movement event is written in the press event.
  10. When the mouse is released, the dragging stops, that is, the mouse movement event can be cancelled
 // 1. 获取元素
        var login = document.querySelector('.login');
        var mask = document.querySelector('.login-bg');
        var link = document.querySelector('#link');
        var closeBtn = document.querySelector('#closeBtn');
        var title = document.querySelector('#title');
        // 2. 点击弹出层这个链接 link  让mask 和login 显示出来
        link.addEventListener('click', function() {
    
    
                mask.style.display = 'block';
                login.style.display = 'block';
            })
            // 3. 点击 closeBtn 就隐藏 mask 和 login 
        closeBtn.addEventListener('click', function() {
    
    
                mask.style.display = 'none';
                login.style.display = 'none';
            })
            // 4. 开始拖拽
            // (1) 当我们鼠标按下, 就获得鼠标在盒子内的坐标
        title.addEventListener('mousedown', function(e) {
    
    
            var x = e.pageX - login.offsetLeft;
            var y = e.pageY - login.offsetTop;
            // (2) 鼠标移动的时候,把鼠标在页面中的坐标,减去 鼠标在盒子内的坐标就是模态框的left和top值
            document.addEventListener('mousemove', move)

            function move(e) {
    
    
                login.style.left = e.pageX - x + 'px';
                login.style.top = e.pageY - y + 'px';
            }
            // (3) 鼠标弹起,就让鼠标移动事件移除
            document.addEventListener('mouseup', function() {
    
    
                document.removeEventListener('mousemove', move);
            })
        })

1.1.6 Case: Imitation of JD Magnifier

  1. The whole case can be divided into three functional modules
  2. Mouse over the small picture box, the yellow occlusion layer and the big picture box are displayed, leave the function of hiding 2 boxes
  3. The yellow occlusion layer follows the mouse function.
  4. Move the yellow occlusion layer, the big picture follows the movement function.

1.1.7. Case study:

  1. The yellow occlusion layer follows the mouse function.
  2. It is not appropriate to give the mouse coordinates to the occlusion layer. Because the occlusion layer coordinates are subject to the parent box.
  3. The first is to get the coordinates of the mouse in the box.
  4. Then the values ​​are given to the occlusion layer as the left and top values.
  5. The mouse movement event is used at this time, but it is still moving in the small picture box.
  6. It was found that the position of the occlusion layer was wrong, and it was necessary to subtract half of the height and width of the box itself.
  7. The occlusion layer cannot exceed the scope of the small picture box.
  8. If it is less than zero, set the coordinates to 0
  9. If it is greater than the maximum moving distance of the occlusion layer, set the coordinates to the maximum moving distance
  10. The maximum moving distance of the occlusion layer: the width of the small picture box minus the width of the occlusion layer box
window.addEventListener('load', function() {
    
    
    var preview_img = document.querySelector('.preview_img');
    var mask = document.querySelector('.mask');
    var big = document.querySelector('.big');
    // 1. 当我们鼠标经过 preview_img 就显示和隐藏 mask 遮挡层 和 big 大盒子
    preview_img.addEventListener('mouseover', function() {
    
    
        mask.style.display = 'block';
        big.style.display = 'block';
    })
    preview_img.addEventListener('mouseout', function() {
    
    
            mask.style.display = 'none';
            big.style.display = 'none';
        })
        // 2. 鼠标移动的时候,让黄色的盒子跟着鼠标来走
    preview_img.addEventListener('mousemove', function(e) {
    
    
        // (1). 先计算出鼠标在盒子内的坐标
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        // console.log(x, y);
        // (2) 减去盒子高度 300的一半 是 150 就是我们mask 的最终 left 和top值了
        // (3) 我们mask 移动的距离
        var maskX = x - mask.offsetWidth / 2;
        var maskY = y - mask.offsetHeight / 2;
        // (4) 如果x 坐标小于了0 就让他停在0 的位置
        // 遮挡层的最大移动距离
        var maskMax = preview_img.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;
        }
        mask.style.left = maskX + 'px';
        mask.style.top = maskY + 'px';
        // 3. 大图片的移动距离 = 遮挡层移动距离 * 大图片最大移动距离 / 遮挡层的最大移动距离
        // 大图
        var bigIMg = document.querySelector('.bigImg');
        // 大图片最大移动距离
        var bigMax = bigIMg.offsetWidth - big.offsetWidth;
        // 大图片的移动距离 X Y
        var bigX = maskX * bigMax / maskMax;
        var bigY = maskY * bigMax / maskMax;
        bigIMg.style.left = -bigX + 'px';
        bigIMg.style.top = -bigY + 'px';

    })

})

1.2. Client series of element visual area

1.2.1 client overview

The client is translated as the client. We use the relevant attributes of the client series to obtain the relevant information of the visual area of ​​the element.
The frame size and element size of the element can be dynamically obtained through the relevant attributes of the client series.
Insert picture description here

Insert picture description here

1.2.2. Taobao flexible.js source code analysis

Execute function immediately (function()())() or (function()()())

Main role: Create an independent scope. Avoid naming conflicts

The following three situations will trigger the load event when the page is refreshed.

1. Hyperlink of a tag

2. F5 or refresh button (forced refresh)

3. Forward and back buttons

But in Firefox, there is a feature, there is a "round trip cache", this cache not only saves the page data, but also saves the state of the DOM and JavaScript; in fact, the entire page is stored in the memory.

So the back button cannot refresh the page at this time.

At this time, you can use the pageshow event to trigger. , This event is triggered when the page is displayed, regardless of whether the page comes from the cache. In the reloading of the page, pageshow will be triggered after the load event is triggered; according to the persisted in the event object to determine whether it is the pageshow event triggered by the page in the cache

注意这个事件给window添加。

1.3. Element scroll scroll series

1.3.1. Scroll overview

The translation of scroll means scrolling. We can dynamically get the size and scroll distance of the element by using the related attributes of the scroll series.
Insert picture description here
Insert picture description here

1.3.2. The head of the page being scrolled

If the height (or width) of the browser is not high enough to display the entire page, a scroll bar will automatically appear. When the scroll bar is scrolled down, the height above the page is hidden, we call it the scrolled head of the page. The scroll bar will trigger the onscroll event when scrolling.

1.3.3. Case: Imitation Taobao fixes the right sidebar

  1. The original sidebar is absolutely positioned
  2. When the page scrolls to a certain position, the sidebar changes to a fixed position
  3. The page continues to scroll, and it will return to the top to display

1.3.4. Case study:

  1. Need to use the page scroll event scroll because it is page scrolling, so the event source is document
  2. Scrolling to a certain position is to judge the upper value of the page being scrolled.
  3. The head of the page being scrolled: you can get the left window.pageXOffset if it is scrolled through window.pageYOffset
  4. Note that the head where the element is scrolled is element.scrollTop, if it is the head where the page is scrolled, it is window.pageYOffset
  5. In fact, this value can be obtained by the offsetTop of the box. If it is greater than or equal to this value, the box can be fixedly positioned.
  //1. 获取元素
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        // banner.offestTop 就是被卷去头部的大小 一定要写到滚动的外面
        var bannerTop = banner.offsetTop
            // 当我们侧边栏固定定位之后应该变化的数值
        var sliderbarTop = sliderbar.offsetTop - bannerTop;
        // 获取main 主体元素
        var main = document.querySelector('.main');
        var goBack = document.querySelector('.goBack');
        var mainTop = main.offsetTop;
        // 2. 页面滚动事件 scroll
        document.addEventListener('scroll', function() {
    
    
            // console.log(11);
            // window.pageYOffset 页面被卷去的头部
            // console.log(window.pageYOffset);
            // 3 .当我们页面被卷去的头部大于等于了 172 此时 侧边栏就要改为固定定位
            if (window.pageYOffset >= bannerTop) {
    
    
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sliderbarTop + 'px';
            } else {
    
    
                sliderbar.style.position = 'absolute';
                sliderbar.style.top = '300px';
            }
            // 4. 当我们页面滚动到main盒子,就显示 goback模块
            if (window.pageYOffset >= mainTop) {
    
    
                goBack.style.display = 'block';
            } else {
    
    
                goBack.style.display = 'none';
            }

        })

1.3.5. Header compatibility solution when the page is scrolled

It should be noted that the scrolled header of the page has compatibility issues. Therefore, the scrolled header usually has the following writing methods:

  1. Declared DTD, use document.documentElement.scrollTop
  2. No DTD declared, use document.body.scrollTop
  3. New methods window.pageYOffset and window.pageXOffset, IE9 began to support
function getScroll() {
    
    
    return {
    
    
      left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft||0,
      top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
    };
 } 
使用的时候  getScroll().left

1.4. Summary of the three major series

Insert picture description here

Their main usage:

1.The offset series is often used to obtain the element position offsetLeft offsetTop

2.client is often used to obtain the size of the element clientWidth clientHeight

3.scroll is often used to get the scroll distance scrollTop scrollLeft

4. Note that the page scroll distance is obtained through window.pageXOffset

1.5. The difference between mouseenter and mouseover

  • The mouseenter event is triggered when the mouse moves over the element
  • Similar to mouseover, the difference between the two is
  • Mouseover will be triggered when the mouse passes through its own box, and when it passes through a child box. mouseenter will only be triggered by its own box
  • The reason for this is because mouseenter does not bubbling
  • Use mouseenter with mouse to leave mouseleave, the same will not bubbling

1.6. Animation function package

1.6.1. Animation realization principle

Core principle: Keep moving the box position through the timer setInterval().

Implementation steps:

  1. Get the current position of the box
  2. Let the box add 1 movement distance to the current position
  3. Use the timer to keep repeating this operation
  4. Add a condition to end the timer
  5. Note that this element needs to add positioning before element.style.left can be used

1.6.2. The animation function records different timers for different elements

If multiple elements use this animation function, declare the timer with var every time. We can use different timers for different elements (use our own timers exclusively).

Core principle: Using JS is a dynamic language that can easily add attributes to the current object.

 function animate(obj, target) {
    
    
            // 当我们不断的点击按钮,这个元素的速度会越来越快,因为开启了太多的定时器
            // 解决方案就是 让我们元素只有一个定时器执行
            // 先清除以前的定时器,只保留当前的一个定时器执行
            clearInterval(obj.timer);
            obj.timer = setInterval(function() {
    
    
                if (obj.offsetLeft >= target) {
    
    
                    // 停止动画 本质是停止定时器
                    clearInterval(obj.timer);
                }
                obj.style.left = obj.offsetLeft + 1 + 'px';

            }, 30);
        }

Guess you like

Origin blog.csdn.net/weixin_48116269/article/details/108082409