簡體   English   中英

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件事。

  1. 當窗口加載時如果#last-child可見,則添加css類.left-fixed
  2. 如果調整窗口大小#last-child可見css類.left-fixed ,如果不可見則將其刪除
  3. 當滾動#last-child可見的CSS類.left-fixed ,如果滾動上不可見,則將其移除。

有人可以指出我實現此目標的方法嗎? 我正在搜索,但找不到這些問題的答案。 感謝您的時間。

很簡單!

jQuery的

if($("#last-child").is(":visible")){
    $(".left").addClass("left-fixed");
}

您可以使用.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/

嘗試這個:

$(document).ready(function(){
  CheckLastVisible();

  $(window).resize(function() {
    CheckLastVisible();
  });
});

function CheckLastVisible(){
  if($("#last-child").is(":visible")){
      $("#last-child").parents(".left:eq(0)").addClass("left-fixed");
  }
  else{
     $("#last-child").parents(".left:eq(0)").removeClass("left-fixed");
  }
}

為此,您必須使用jquery:

//When window load if #last-child is visible add css class .left-fixed

if($("#last-child").is(":visible")){
    $(this).parent().addClass("left-fixed");
}

//If window is resize #last-child visible css class .left-fixed and remove if //not visible
if($("#last-child").is(":visible")){
    $(this).parent().addClass("left-fixed");
}
else{
   $(this).parent().removeclass("left-fixed");
}

//還有一種無需使用jquery的方法:

.last-child{ display:none; }
.parent:hover .last-child{ display:block; }

你可以像下面這樣

$(document).ready(function(){
 iflastvisible();

  $(window).resize(function() {
    iflastvisible();
  });
});

function iflastvisible(){
  if($("#last-child").is(":visible")){
      $("#last-child").parents(".left:eq(0)").addClass("left-fixed");
  }
else{
 $("#last-child").parents(".left:eq(0)").removeClass("left-fixed");
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM