gpt4 book ai didi

javascript - 如果元素超出视口(viewport),则将类添加到元素

转载 作者:行者123 更新时间:2023-11-30 08:37:03 26 4
gpt4 key购买 nike

我正在使用导航下拉菜单,它有几个下拉选项。所以我想添加一个 move-left 类,如果它超出视口(viewport)边缘。

我试过 getBoundingClientRect(); 但它给了我以下错误:

Uncaught TypeError: el.getBoundingClientRect is not a function

我的浏览器是 chrome 最新版本。

我的代码是:

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')
}
})

最佳答案

您正在尝试通过 jQuery 对象访问属于 native DOM 元素的方法。

因此,您需要更改这一行:

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

对此:

// 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];

关于javascript - 如果元素超出视口(viewport),则将类添加到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30389142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com