简体   繁体   English

如果元素不在视口中,则将其添加到元素中

[英]Adding class to an element if it is out of viewport

I am working with a navigation dropdown and it has several dropdowns options. 我正在使用导航下拉菜单,它具有多个下拉菜单选项。 So I want to add a class move-left if it goes out of the viewport edge. 所以我想添加一个类move-left如果它超出视口边缘。

I have tried getBoundingClientRect(); 我已经尝试过getBoundingClientRect(); but it gives me following error : 但是它给了我以下错误:

Uncaught TypeError: el.getBoundingClientRect is not a function 未捕获的TypeError:el.getBoundingClientRect不是函数

My browser is chrome latest version. 我的浏览器是chrome最新版本。

My code is: 我的代码是:

var isElemInViewport = function(el){
    var rect = el.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&     
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

var el = $('ul.nav-menu li ul li ul');
$('ul.nav-menu li ul li').hover(function(){
    if(!isElemInViewport(el)){
        alert('o ya')
    }
}, function(){
     if(!isElemInViewport(el)){
        alert('no more')
     }
})

You are trying to access a method that belongs to native DOM elements, through a jQuery object. 您正在尝试通过jQuery对象访问属于本机DOM元素的方法。

So, you need to change this line: 因此,您需要更改此行:

var el = $('ul.nav-menu li ul li ul');

To this: 对此:

// The jQuery object, at property '0', contains the native DOM element
// you want. If you were to get multiple matches for your selector,
// they'll be numbered in order: 
// $('selector')[0], $('selector')[1], $('selector')[2], ...

var el = $('ul.nav-menu li ul li ul')[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM