您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页香草js侦测元素是否离开视窗viewport

香草js侦测元素是否离开视窗viewport

来源:伴沃教育

很多时候,我们需要检查一个元素是否已经部分不在或者全部不在视窗区域,当这种现象发生时做相应的处理。

比如在CMS编辑内容时,其工具菜单很有可能因为内容区域过长导致滑出视窗区域,而工具栏又是经常要使用的,这就非常不便。

那么如何检查这种情况呢?我们来看看 getBoundingClientRect() 函数吧。

element.getBoundingClientRect()调用将返回一个对象,该对象包含了该元素相对于viewport的top,bottom,left,和right的位置。

我们看看以下代码:

var elem = document.querySelector('#some-element');
var bounding = elem.getBoundingClientRect();

// Returns something like this:
// {top: -123, left: 0, right: 0, bottom: 25}
console.log(bounding);

我们可以通过简单的数学比较来检查是否元素已经跑到了viewport的外部。

如果bounding.top或者bounding.left小于0,那么top或者left部分已经不在viewport里面。如果bounding.right大于viewport.width或者bounding.bottom大于viewport.height,则right或者bottom部分就不在viewport里面了。

if (bounding.top < 0) {
    // Top is out of viewport
}

if (bounding.left < 0) {
    // Left side is out of viewoprt
}

if (bounding.bottom > (window.innerHeight || document.documentElement.clientHeight)) {
    // Bottom is out of viewport
}

if (bounding.right > (window.innerWidth || document.documentElement.clientWidth)) {
    // Right side is out of viewport
}

需要注意的是并不是所有的浏览器都支持window.innerWidth和window.innerHeight,因此我们必须有能力回滚兼容到document.documentElement.clientWidth和document.documentElement.cleintHeight属性上面。

写一个helper函数:

/*!
 * Check if an element is out of the viewport
 * (c) 2018 Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {Node}  elem The element to check
 * @return {Object}     A set of booleans for each side of the element
 */
var isOutOfViewport = function (elem) {

    // Get element's bounding
    var bounding = elem.getBoundingClientRect();

    // Check if it's out of the viewport on each side
    var out = {};
    out.top = bounding.top < 0;
    out.left = bounding.left < 0;
    out.bottom = bounding.bottom > (window.innerHeight || document.documentElement.clientHeight);
    out.right = bounding.right > (window.innerWidth || document.documentElement.clientWidth);
    out.any = out.top || out.left || out.bottom || out.right;
    out.all = out.top && out.left && out.bottom && out.right;

    return out;

};

随后,我们通过下面的代码来简单调用检查是否不在viewport中:

var elem = document.querySelector('#some-element');
window.addEventListener( 'scroll', handler )
function handler(){
var isOut = isOutOfViewport(elem); if (isOut.top) { // Top is out of viewport } if (isOut.left) { // Left side is out of viewoprt } if (isOut.bottom) { // Bottom is out of viewport } if (isOut.right) { // Right side is out of viewport }
if (isOut.any) { // At least one side of the element is out of viewport } if (isOut.all) { // The entire element is out of viewport }
}
 

 

 

 

转载于:https://www.cnblogs.com/kidsitcn/p/11599114.html

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务