2012-10-02 154 views
0

我在嘗試使淡入淡出效果正常工作時遇到了一些困難。我認爲我過分複雜了。JavaScript淡入淡出問題

我有4張圖片,但只有前兩張需要淡出,並懸停在圖片上(其他兩張圖片與頁面上的其他功能一起使用)。

我的HTML是:

<div class="square"> 
    <div class="imageHolder">  
     <!--Comment out and uncomment BG image to show transitions on BG images-->  
     <img class="one" src="image_01.jpg" /> 
     <img class="two" src="image_02.jpg" /> 
     <img class="three" src="image_03.jpg" /> 
     <img class="four" src="image_04.jpg" /> 
    </div> 
</div> 

形象,二,三,四,顯示無

JS:

$('.square').mouseover(function() { 
      $(this).find('img').each(function() { 
       if ($(this).attr('class') === 'two') { 
        $(this).fadeIn('slow'); 
       } 
       if ($(this).attr('class') === 'one') { 
        $(this).fadeOut('slow'); 
       } 
      }); 
    }); 

任何幫助將非常感激。

感謝您的回覆。

我試圖太聰明,它並不需要它。有沒有一種方法可以讓淡入淡出同時發生而不用插件?

+2

你真的應該,如果你使用hasClass()要去看看它是否有班級。 – epascarello

+0

在代碼中發佈的答案如果應該同時發生。你是什​​麼意思*不使用插件*?不使用jQuery?如果是這樣,是否有任何理由不想使用它?嗯,可以這樣做,但它需要更多的代碼,然後你應該確保它在不同的瀏覽器上正常工作,因爲瀏覽器的差異。 –

+0

使用jQuery,但沒有額外的插件,在一分鐘後,它會淡出默認圖像,然後淡入新圖像。理想情況下,它需要同時發生。 – AidenJH

回答

1

嘗試做這樣的:

$(".one").fadeIn("slow", function() { $(this).fadeOut("slow") }); 
$(".two").fadeIn("slow", function() { $(this).fadeOut("slow") }); 

更新:

我誤解你的問題,我想您想既淡入和淡出。爲了使第一個淡入和第二淡出使用這樣的事情:

$(".one").fadeIn("slow"); 
$(".two").fadeOut("slow"); 

如果你有onetwo類等元素,不希望影響到他們,你可以輸入$(".imageHolder .one")$(".imageHolder .two")代替的$(".one")$(".two")

如果你有你的頁面上有多個imageHolder元素,使用find()功能由epascarello舒尚特·雷迪的建議。

1

爲什麼每個人不只是選擇他們?

var imgs = $(this).find("img"); 
imgs.filter(".one").fadeOut('slow'); 
imgs.filter(".two").fadeIn('slow'); 

var imgs = $(this); 
imgs.find(".one").fadeOut('slow'); 
imgs.find(".two").fadeIn('slow'); 
+0

謝謝,有沒有一種方法的淡入淡出和同時發生,而不使用jQuery以外的插件? – AidenJH

0

你不需要。每個循環..只要找到DIV中的IMG和做您的操作

試試這個..

$('.square').mouseover(function() { 

    $(this).find('.two').fadeIn('slow'); 
    $(this).find('.one').fadeOut('slow'); 

});​ 

Check FIDDLE

0

我認爲這是你在找什麼:

$('.square img') 
    .mouseover(function() { 
     $(this).fadeIn('slow'); 
    }) 
    .mouseout(function() { 
     $(this).fadeOut('slow'); 
    }); 
0

我想你會更好地使用jquery.hoverIntent.js。當你將光標快速移動到不同的圖像上時,它會產生一點延遲時間。

爲例

$(document).ready(function(){ 
    var config = {  
    interval: 230, 
    over: zoomIn, 
    out: zoomOut 
    }; 

    $("div#clients_wrap div").hoverIntent(config); 

    }); 

zoomIn EN縮小(ZoomOut)的功能,你可以用淡入聲明它們分別淡出。這只是一個改進。

0

基本上是一個類分配給需要淡入/淡出懸停在該組圖像的輸入/輸出分別

<div class="square"> 
     <div class="imageHolder">  
      <!--Comment out and uncomment BG image to show transitions on BG images-->  
      <img class="one fadeeffect" src="image_01.jpg" /> 
      <img class="two fadeeffect" src="image_02.jpg" /> 
      <img class="three" src="image_03.jpg" /> 
      <img class="four" src="image_04.jpg" /> 
     </div> 
    </div> 

的javascript:

$('.fadeeffect')..hover(function(){ 
    // write your code here 
}