2017-01-03 5 views
0

どのように兄弟に行くの?ユーザーがスクロール要素の位置にページと、私はこのコードを使用するとき、私は要素にクラスを追加するコードを持っている特定のクラスまたはIDを持たない特定の要素のためのaddClass

$(window).on('scroll',function(){ 
    Scroll = $(this).scrollTop(); 
     if(Scroll >= $('img').position().top) 
     $('img').addClass('rotate'); 
    }); 

そして、私のhtmlコードはこれです:

<div class="some-class"> 
    <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size"> 
</div> 

<div class="some-class"> 
    <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size"> 
</div> 

<div class="some-class"> 
    <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size"> 
</div> 

コードを実行すると、rotateクラスがすべてのimgタグに適用されます。私はrotateクラスを、私のjs if文で述べた条件を持つ要素に追加したいと思っています!

ここで私は何ができますか? jsfiddleも表示されます。すべてimg

答えて

3

ループとあなたが好き、あなたの条件に合った画像のみタグを取得するjQueryのfilterを使用することができますクラス

$(window).on('scroll',function(){ 
    Scroll = $(this).scrollTop(); 
    $('img').each(function(){ 
    if(Scroll >= $(this).position().top) 
     $(this).addClass('rotate'); 


     }); 

}); 
3

を追加するために$(this)を使用します。

Scroll = $(this).scrollTop(); 
$('img').filter(function(index, el) { 
    return Scroll >= el.position.top(); 
}).addClass('rotate'); 
+0

おかげで多くのことを伝えるためにthisコンテキストを使用:)しかし、私はそれが私のために動作しませんでしたと思う: - ??あなたはもっとそれを説明できますか? – JustCauseWhat

0

すると、あなたの場合を置き換えますこれを伴う声明

$('img').each(function(index) { 
if(Scroll >= $(this).position().top) 
    $(this).addClass('rotate'); 

});

+0

ありがとう:) – JustCauseWhat

0

$(window).on('scroll', function() { 
 
    Scroll = $(this).scrollTop(); 
 
    $('img').each(function() { 
 
    if (Scroll >= $(this).position().top) 
 
     $(this).addClass('rotate'); 
 
    }) 
 

 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="some-class"> 
 
    <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size"> 
 
</div> 
 

 
<div class="some-class"> 
 
    <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size"> 
 
</div> 
 

 
<div class="some-class"> 
 
    <img src="http://blog.majidkn.com/wp-content/themes/majidkn2/images/mkn.png" class="feature-size"> 
 
</div>

各画像を繰り返し処理し、その後、現在の画像に

関連する問題