亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

當div是視口頂部的x個像素時添加一個類

當div是視口頂部的x個像素時添加一個類

呼如林 2021-12-02 15:19:00
我想要的是在 div 中添加一個類,例如,在視口頂部的 100 像素處。所以不是在滾動 100 像素之后,而是當它在視口頂部下方 100 像素時。有人可以幫我解決這個問題嗎?<script>jQuery(function() {    //caches a jQuery object containing the header element    var header = jQuery('#v0');    jQuery(window).scroll(function() {        var scroll = jQuery(window).scrollTop();        if (scroll >= 2939) {            header.addClass('fixed1'); }    else {            header.removeClass('fixed1');        }    });});</script>
查看完整描述

1 回答

?
開心每一天1111

TA貢獻1836條經驗 獲得超13個贊

不確定這是否正是您想要實現的,但這是代碼。如果標題距窗口頂部的距離超過 100 像素(這不是很常見,因為標題頂部應該有一些東西),那么新類將添加到標題中。


$(function() {  

  var $header = $('#v0');

  $(window).scroll(function () { 

    if ($header.offset().top - $(this).scrollTop() > 100) {

      $header.addClass('blabla');

    } else {

      $header.removeClass('blabla');

    }

  });

});

更新:根據您的反饋,這是我想到的第一個解決方案。我認為這就是你需要的行為。希望對你有用:


$(function() {  

  var $header = $('header');

  var $video = $('#v0');

  var $videoContainer = $('.videoContainer');


  $(window).scroll(function () {

    // Here we check if video field touches the header, and add 'fixed' class

    if ((($header.offset().top + $header.height()) - $video.offset().top) >= 0) {

      $video.addClass('fixed')

    }

    // Since both video and header is fixed now I needed some other

    // element to check if we are again getting away from the header

    // (scrolling up again) That's why I added the $videoContainer element 

    // to be able to remove the 'fixed' class.

    if ($videoContainer.offset().top > ($header.offset().top + $header.height())) {

      $video.removeClass('fixed');

    }

  });

});

更新代碼:https : //jsbin.com/foyoyus/6/edit?html,css,js,output


查看完整回答
反對 回復 2021-12-02
  • 1 回答
  • 0 關注
  • 157 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號