2015-10-15 63 views
0

我試圖讓一個div向上拓展上懸停,然後返回到原來的高度上鼠標移開。很簡單。 div位於絕對位置,bottom:0,因此它緊貼在其父代的底部。問題在於我無法控制div中內容的長度,所以最高值設置爲auto。jQuery的歸元到原來的位置

因此,我需要計算實際頂端的位置,則該值傳遞給第二功能在懸停(),它處理鼠標移開動畫,以恢復其原始高度。

$('#blog3 .blog-grid li').hover(
    function() { // mouse over 
     // calculate .content-box top position 
     var offset = $(this).find(".content-box").offset().top - $(this).find(".content-box").parent().offset().top; 

     // darken the box 
     $(this).find(".content-box").css("background-color", "rgba(0,0,0,0.5)").animate({ 
      queue: false, 
      duration: 500 
     }); 

     // expand the content div 
     $(this).find(".content-box").stop(true,true).animate({ 
      top: 0, 
     }, { 
      queue : false, 
      duration : 500 
     }); 

     $(this).find("p").fadeIn("slow"); 
     $(this).find(".read-more").stop(true,true).fadeIn("slow"); 
    }, 
    function() { // mouse out 
     $(this).find(".content-box").css("background-color", "transparent").animate({ 
      queue: false, 
      duration: 500 
     }); 

     $(this).find(".content-box").stop(true,true).animate({ 
      top: offset + 'px', // <-- restore to original position 
     }, { 
      queue : false, 
      duration : 500 
     }); 

     $(this).find("p").stop(true,true).fadeOut("slow"); 
     $(this).find(".read-more").stop(true,true).fadeOut("slow"); 
    } 
); 

問題,當然,是,我無法通過「偏移」變量設置爲第二(鼠標移開)功能,也不能我聲明「偏移」作爲一個全局變量,因爲它需要按懸停計算。

我敢肯定,必須有另一種方式來這個數字傳遞給第二個功能,但我似乎無法推測出來......

回答

0

回答我自己的問題;)

套裝'offset'作爲全局變量,然後在mouseover函數內執行位置計算。

var offset = null; 
$('#blog3 .blog-grid li').hover(
    function() { 
     //get .content-box top position 
     offset = $(this).find(".content-box").offset().top - $(this).find(".content-box").parent().offset().top; 

     // darken the box 
     $(this).find(".content-box").css("background-color", "rgba(0,0,0,0.5)").animate({ 
      queue: false, 
      duration: 500 
     }); 

     // initialize position 
     $(this).find(".content-box").css("top", offset); 

     // expand the content div 
     $(this).find(".content-box").stop(true,true).animate({ 
      top: 0, 
     }, { 
      queue : false, 
      duration : 500 
     }); 

     $(this).find("p").fadeIn("slow"); 
     $(this).find(".read-more").stop(true,true).fadeIn("slow"); 
    }, 
    function() { 
     $(this).find(".content-box").css("background-color", "transparent").animate({ 
      queue: false, 
      duration: 500 
     }); 

     $(this).find(".content-box").stop(true,true).animate({ 
      top: offset + 'px', 
     }, { 
      queue : false, 
      duration : 500 
     }); 

     $(this).find("p").stop(true,true).fadeOut("slow"); 
     $(this).find(".read-more").stop(true,true).fadeOut("slow"); 
    } 
); 
相關問題