2013-01-18 36 views
2

在頁面上我有多個大拇指圖片,每個圖片都有自己的id,由php生成。多個項目的jQuery動畫

我需要爲每個元素做jQuery動畫。

我卡在這裏,我怎麼可以檢測到女巫thumb_id-??用戶是懸停,並動畫呢?

我知道我可以爲onmouseover/out做兩個簡單的js函數,並通過id ..但是還有另一種使用jQuery的方法嗎?

<script> 
$(document).ready(function(){ 
    $('#thumb_id- ??? ').mouseover(function(){ 
       div = $('div.thumb-img-hover'); 
       div.animate({opacity: '1'}, 150); 
    }).mouseout(function(){ 
       div.animate({opacity: '0'}, 150); 
    }); 
}); 
</script> 

foreach($arr as $val){ 
    echo ' 
    <a class="group1" text="TESTING" title="" href="'.$baseurl.'uploads/'.$val["filename"].'"> 
    <div class="thumb-img-container right"> 
    <div class="thumb-img" style="position:relative;background:url(\''.$baseurl.'uploads/thumbs/'.$val["filename"].'\') no-repeat center center;background-size: cover;"> 
    <div id="thumb_id-'.$val["id"].'" class="thumb-img-hover"><a href="'.$baseurl.'index.php?action=image&id='.$val["id"].'">test</a></div> 
    </div> 
    </div> 
    </a> 
    '; 
} 
+1

爲什麼不使用類選擇? – undefined

+0

給所有的拇指一個類,並使用類選擇器:'$('。thumb_class')'。 – Manuel

+0

我試過了,但是如果我徘徊在物品上。所有項目都會獲得動畫,不僅是我徘徊的動畫。 – Fr0z3n

回答

3

您可以使用屬性與選擇,$('div[id^=thumb_id]')開始,但爲什麼不使用類選擇?

$(document).ready(function(){ 
    $('div.thumb-img-hover').mouseenter(function(){ 
     $(this).stop().animate({opacity: '1'}, 150); // this refers to the current element 
    }).mouseleave(function(){ 
     $(this).stop().animate({opacity: '0'}, 150); 
    }); 
}); 

您還可以使用CSS:

div.thumb-img-hover { 
    opacity: 0.5; 
    -webkit-transition: opacity 150ms; 
    -moz-transition: opacity 150ms; 
    -o-transition: opacity 150ms; 
    transition: opacity 150ms; 
} 
div.thumb-img-hover:hover { 
    opacity: 1; 
} 
+0

我正面臨一個小問題。正如你所看到的,DIV內部有一個鏈接,當鼠標在DIV上移動然後在鏈接上時,動畫重新開始。我怎麼能阻止呢? – Fr0z3n

+0

@DjRikyx這是因爲你使用'mouseover',而是使用'mouseenter/mouseleave'。我已經更新了答案。 – undefined

+0

非常感謝:) – Fr0z3n