在滚动上改变颜色

时间:2016-07-23 22:16:06

标签: javascript jquery css

尝试将类添加到img和title(h3)以更改颜色。它正在努力将类添加到.test-shadow,但是h3不起作用。尝试将兄弟姐妹改成.closest / .find,但他们也没有工作。想法?



	          /* highlight border of winner */
        $('.img-winner').each( function(i){
            
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();
            
            /* If the object is completely visible in the window, animate border or box shadow */
            if( bottom_of_window > bottom_of_object ){
                
			$(this).siblings('.test-shadow:first').addClass('greenit');
			  $(this).siblings('h3.test-who-us:first').addClass('green');
                    
            }
            
        }); 

<ul class="2-column center test-images">
<li>
<h3 class="test-who-us">Medsite Medical</h3>
<div class="test-img">
<img class="img-winner" src="/wp-content/uploads/2016/07/test-desktop-us.png" alt="test-desktop">
<div class="test-shadow"></div>
</div>
</li>
<li>
<h3 class="test-who-them">Top competitor</h3>
<div class="test-img">
<img class="img-loser" src="/wp-content/uploads/2016/07/test-desktop-them.png" alt="test-desktop-competitors">
<div class="test-shadow"></div>
</div>
</li>
</ul>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

<h3.img-winner的父级的兄弟。

所以用$(this).siblings('h3.test-who-us:first')

替换$(this).parent().siblings('h3.test-who-us:first')

/* highlight border of winner */
$('.img-winner').each(function(i) {

  var bottom_of_object = $(this).offset().top + $(this).outerHeight();
  var bottom_of_window = $(window).scrollTop() + $(window).height();

  /* If the object is completely visible in the window, animate border or box shadow */
  if (bottom_of_window > bottom_of_object) {

    $(this).siblings('.test-shadow:first').addClass('greenit');
    $(this).parent().siblings('h3.test-who-us:first').addClass('green');

  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="2-column center test-images">
  <li>
    <h3 class="test-who-us">Medsite Medical</h3>
    <div class="test-img">
      <img class="img-winner" src="/wp-content/uploads/2016/07/test-desktop-us.png" alt="test-desktop">
      <div class="test-shadow"></div>
    </div>
  </li>
  <li>
    <h3 class="test-who-them">Top competitor</h3>
    <div class="test-img">
      <img class="img-loser" src="/wp-content/uploads/2016/07/test-desktop-them.png" alt="test-desktop-competitors">
      <div class="test-shadow"></div>
    </div>
  </li>
</ul>

答案 1 :(得分:0)

不需要每个循环。 jQuery选择器已遍历HTML,抓取所有适用的元素。还不需要在滚动事件上创建监视器。如果具有img-winner类的元素已经在文档中而不在页面上,那么继续设置它或在HTML中添加类更有效。渲染后更改内容通常会导致重排。 Prevent Browser Reflow

然而,这就是您根据HTML代码实现所需目标的方法。

var $winnerElem = $('.img-winner'); // cache the winner element

// add classes
$winnerElem.addClass('greenit');
$winnerElem.parent().siblings().addClass('green');