jQuery仅在最后一个子元素可见时才添加css类(jQuery add css class only when last child element is visible)

编程入门 行业动态 更新时间:2024-10-12 03:22:03
jQuery仅在最后一个子元素可见时才添加css类(jQuery add css class only when last child element is visible)

如果最后一个孩子在可见范围内,我想向父母添加一个css类。

HTML

<div class="container"> <div class="left"></div> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> More items will be here <li id="last-child">Last item</li> </ul> <div class="right"> <p> Some content </p> </div> </div>

CSS

.left{position:absolute;} .left-fixed{position:fixed;}

因此,当#last-child在可见范围内时,我想将css类.left-fixed添加到div类.left

我想要实现的3件事。

当窗口加载时,如果#last-child可见,则添加css类.left-fixed 如果窗口调整大小#last-child visible css class .left-fixed ,如果不可见则删除 滚动#last-child visible css class .left-fixed并删除如果在滚动时不可见。

有人能指出我实现这一目标的方法吗? 我搜索但找不到这些问题的答案。 感谢你的时间。

I want to add a css class to parent if the last child is in visible range.

HTML

<div class="container"> <div class="left"></div> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> More items will be here <li id="last-child">Last item</li> </ul> <div class="right"> <p> Some content </p> </div> </div>

CSS

.left{position:absolute;} .left-fixed{position:fixed;}

So when the #last-child is in visible range I want to add css class .left-fixed to div class .left

3 things I want to achieve.

When window load if #last-child is visible add css class .left-fixed If window is resize #last-child visible css class .left-fixed and remove if not visible When scroll #last-child visible css class .left-fixed and remove if not visible on scroll.

Can someone point me a way to achieve this? I search but couldn’t find an answer to these questions. Appreciate your time.

最满意答案

您可以使用.getBoundingClientRect() , window.innerHeight

const last = $("#last-child")[0]; const left = $(".left"); $(window).on("resize", function(event) { if ((last.getBoundingClientRect().top < -(last.clientHeight) || last.getBoundingClientRect().bottom > window.innerHeight)) { if (!left.is(".left-fixed")) { left.addClass("left-fixed"); } } else { if (left.is(".left-fixed")) { left.removeClass("left-fixed") } } }).resize();

jsfiddle https://jsfiddle.net/hfv89veu/3/

You can use .getBoundingClientRect(), window.innerHeight

const last = $("#last-child")[0]; const left = $(".left"); $(window).on("resize", function(event) { if ((last.getBoundingClientRect().top < -(last.clientHeight) || last.getBoundingClientRect().bottom > window.innerHeight)) { if (!left.is(".left-fixed")) { left.addClass("left-fixed"); } } else { if (left.is(".left-fixed")) { left.removeClass("left-fixed") } } }).resize();

jsfiddle https://jsfiddle.net/hfv89veu/3/

更多推荐

本文发布于:2023-08-07 05:26:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1460684.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时才   个子   元素   css   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!