更改滚动背景颜色不按预期工作

时间:2017-05-28 09:32:26

标签: jquery html css scroll

如果滚动位置小于10,我想将#section2的背景颜色更改为绿色,如果滚动位置大于10,则将其更改为绿色。

下面的代码没有按预期工作,我该如何修复此Fiddle

$(window).scroll(function() {
        if ($(document).scrollTop() <= 10) {
            $('#section2').addClass('greeen');
        }
        else {
            $('#section2').addClass('reed');
        }
    });

3 个答案:

答案 0 :(得分:0)

您需要使用removeClass()方法删除其他类。

$(window).scroll(function() {
    if ($(document).scrollTop() <= 10) {
        $('#section2').removeClass('reed').addClass('greeen');
    }
    else {
        $('#section2').addClass('reed').removeClass('greeen');
    }
});

答案 1 :(得分:0)

试试这个:

    $(window).scroll(function() {
        if ($(document).scrollTop() <= 10) {
            $('#section2').removeClass('reed').addClass('greeen');
        }
        else {
            $('#section2').removeClass('green').addClass('reed');
        }
    });

答案 2 :(得分:0)

添加red时必须删除课程green,反之亦然

$(window).scroll(function() {
  if ($(document).scrollTop() <= 10) {
    $('#section2').addClass('green');
     $('#section2').removeClass('red');
  } else {
     $('#section2').removeClass('green');
      $('#section2').addClass('red');
  }
});

redgreen(不是reedgreeen

也有拼写错误

检查此代码段

$(window).scroll(function() {
  if ($(document).scrollTop() <= 10) {
    $('#section2').addClass('green');
     $('#section2').removeClass('red');
  } else {
     $('#section2').removeClass('green');
      $('#section2').addClass('red');
  }
});
section {
  padding: 100px;
  height: 100px;
  background: rgba(0, 0, 0, .2);
}

section:nth-of-type(even) {
  color: white;
  background: rgba(0, 0, 0, .9);
}

section.in-view img {
  opacity: 1;
}

img {
  opacity: 0;
  transition: opacity 1s ease-out;
}

.red {
  background: #f00 !important;
}

.green {
  background: green !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="section1">
  <h1>Section 1</h1>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet placeat, excepturi, necessitatibus assumenda id blanditiis quam molestiae voluptates, reiciendis delectus a dolor at. Assumenda voluptatem tenetur officiis perspiciatis, architecto quos!</p>
  <img src="http://fillmurray.com/400/400">
</section>
<section id="section2">
  <h1>Section 2</h1>
  <p>Est laudantium animi eius asperiores magni perspiciatis facere repudiandae nemo provident facilis ipsum, repellat illum unde qui incidunt ea, veniam. Soluta unde, doloremque dolore culpa, repellat tempora iure labore maxime.</p>
  <img src="http://fillmurray.com/400/400">
</section>
<section id="section3">
  <h1>Section 3</h1>
  <p>Quis magni, id, cum odio laborum impedit veritatis, reprehenderit nisi voluptatum ipsum animi itaque officia! Eius magni ipsa animi nostrum placeat, consequuntur nam odit, impedit architecto quod ipsum reiciendis deserunt.</p>
  <img src="http://fillmurray.com/400/400">
</section>