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/
更多推荐
发布评论