2017-01-03 61 views
0

布魯斯如何布萊恩?addClass僅用於沒有特定類別或ID的特定元素

我有一個要添加一個類元素碼當用戶滾動頁面的元素位置,我用這個代碼:

$(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

回答

3

循環到所有img和使用$(this)添加類

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


     }); 

}); 
3

您可以使用jQuery的filter只得到一個適合您的需求,像圖像標籤:

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

感謝很多:)但我認爲這並沒有爲我工作: - ??你能解釋一下嗎? – 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>

迭代通過每幅圖像,然後使用this方面告訴當前圖像