JavaScript daily Tips

Viewport

On the PC side, the viewport refers to a visual area of the browser, the width of the browser window and consistent. It can also be called the viewable area.
There is the browser scroll bar, then how do we find an element is in the visible region of it, we need the help of Element.getBoundingClientRect ()
The implication is that they are returned to the size and position relative to the viewport, as

Returns the object

First we get the visible area

/**
获取视口
**/
function getViewportOffset() {
    if (window.innerWidth) {
        return {
            w: window.innerWidth,
            h: window.innerHeight
        }
    } else {
        if (document.compatMode == "BackCompat") {
            return {
                w: document.body.clientWidth,
                h: document.body.clientHeight
            }
        } else {
            return {
                w: document.documentElement.clientWidth,
                h: document.documentElement.clientHeight
            }
        }
    }
}
/**
判断是否在元素是否在是视口内
**/
function isElementInViewport(ele) {
    var vp = getViewportOffset() 
    var rect = ele.getBoundingClientRect();
    console.log("top:"+rect.top+",left:"+rect.left+",bottom:"+rect.bottom+",right:"+rect.right);
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= vp.h &&
        rect.right <= vp.w
    );
}

Custom Attributes

Html5 added a new feature, which is data- custom attributes. Looks like not to. . . This would have is that you can not custom attributes, and then read through the getAttribute it, yes, no problem, html5 just made its unity, and read data- custom property also provides a new interface

<div style="width: 100px;height:100px;background-color:red;" data-src="cs"></div>
<script>
   var div = document.getElementsByTagName("div")[0];
   var data = div.dataset.src;  //cs
</script>

Guess you like

Origin www.cnblogs.com/FashionDoo/p/10947436.html