2013-02-23 22 views
-1

Ergo:爲什麼不做這項工作?有人可以幫我在jquery中獲取div類嗎?

我想製作一個動畫功能,它必須根據其名稱更改css div的位置。 例如,產品1不需要更改其頂部位置,產品2就可以,產品3必須更多。

一直在這掙了幾個小時!

if($(this).attr("class") = "product1") 
     { 
      $(this).cssAnimate({height: '100%',marginBottom:'-350px'}, {duration: 400}); 
     } 
     else if($(this).attr("class") = "product2") 
     { 
      $(this).cssAnimate({top:'-176px',height: '100%',marginBottom:'-350px'}, {duration: 400}); 
     } 
     else if($(this).attr("class") = "product3") 
     { 
      $(this).cssAnimate({top:'-352px',height: '100%',marginBottom:'-350px'}, {duration: 400}); 
     } 
     else 
     { 
     return false; 
     } 

回答

0

考慮的東西接近這個:

var topPx; 
var productClass = $(this).attr("class"); 

switch (productClass) { 
    case "product1": topPx = "0px"; break; 
    case "product2": topPx = "-176px"; break; 
    case "product3": topPx = "-353px"; break; 
    default: return false; 
} 

$(this).cssAnimate({ 
    top:   topPx, 
    height:  '100%', 
    marginBottom: '-350px' 
}, { 
    duration: 400 
}); 

有一噸的方式來寫這篇文章,但我傾向於對通信的目標,並消除重複冗餘。例如,沒有理由繼續獲得"class"屬性;大概它不會改變這個代碼的生命週期。 cssAnimate的參數除單個條目外是相同的,所以只更改該條目是有意義的。

我對在switch語句中使用return並不興奮。選項包括明確的比較,檢查的productClass在數組值等的存在也將是易於使用的地圖一類的像素偏移:

var offsets = { 
    "product1": "0px", 
    "product2": "-176px", 
    "product3": "-353px" 
}; 

var productClass = $(this).attr("class"); 
var offset = offsets[productClass]; 
if (offset === undefined) { 
    return false; 
} 

$(this).cssAnimate({ 
    top:   offset, 
    height:  '100%', 
    marginBottom: '-350px' 
}, { 
    duration: 400 
}); 

您可能需要來包裝起來的方法獲取偏移量,或者可能返回將與默認地圖合併的選項地圖。

+0

非常感謝,效果很棒! 我其實不知道任何jquery,我只是摸索,你真的很有幫助。 – user2101355 2013-02-23 08:42:48

1

您需要將「=」更改爲「==」作爲開始。

+0

是的,我已經兩個人,但那不是問題。 – user2101355 2013-02-23 08:43:22

相關問題