使用JQuery基于div / section更改的ADD / REMOVE类

时间:2016-11-21 14:19:27

标签: javascript jquery html css

我有一个固定的图像,我需要根据div / section changes

对其进行动画处理
<div class="fixed">
  <img src="some_image.jpg" class="child-fixed">
</div>

<section class="section" id="section-1">
//this is rotating section
</section>
<section class="section" id="section-2">
//this is flip section
</section>

和CSS看起来像这样,

.fixed{
position:fixed;
margin:50% auto;
width:50px;
height:50px;
}
.fixed-child{
width:100%;
height:100%;
margin:0;
padding:0;
}
.section{
height:100vh;
width:100vw;
}
.rotate{
//some css totate styles here
}
.flip{
//some css flip styles here
}

和JQuery Code就是这样,

$(document).ready(function(){
$(window).scroll(function(){
if ($(window).scrollTop() > 100){
    $('.fixed-child').addClass( "rotate");
 }elseif($(window).scrollTop() > 200){
    $('.fixed-child').addClass( "flip");
  }
 });
});

现在我需要在第1节上的图像上添加旋转类并删除旋转类,并在第2部分使用jquery时添加翻转类,

我搜索了一下,我发现了一些例子,但是使用这些例子我可以基于jquery scrollTop()方法添加/删除类,但我希望jquery检测该类并在我向下滚动并向上滚动时添加相应的类反之亦然。

我没有编写旋转和翻转CSS代码来减少这里的行数。但那些翻转和旋转工作。

请帮助我实现这种风格!

2 个答案:

答案 0 :(得分:1)

从我的问题/评论中我可以收集到的内容,例如Waypoints

  

当您滚动到时,Waypoints是触发功能的最简单方法   一个元素。

答案 1 :(得分:1)

我也会使用路标来做这样的事情,但作为替代方案,你可以尝试做类似的事情:

$( document ).ready(function() {

    var section_1 = $('#section-1'),
        section_2 = $('#section-2');

    $(window).scroll(function() {
      var scroll_lvl = $(document).scrollTop(),
          section_1_lvl = section_1.offset().top,
          section_2_lvl = section_2.offset().top;

      if(scroll_lvl >= section_1_lvl && scroll_lvl < section_2_lvl) {
           $('.fixed-child').addClass( "rotate");
           $('.fixed-child').removeClass( "flip");
      } else if (scroll_lvl > section_1_lvl && scroll_lvl >= section_2_lvl) {
           $('.fixed-child').addClass( "flip");
           $('.fixed-child').removeClass( "rotate");
      }


    });

});