2012-09-10 36 views
1

我剛在我們網站的一部分實現了一個簡單的展開/摺疊系統。我嘗試了一些現有的解決方案,但它只是覺得需要花費很多努力才能適應網站,所以我編寫了自己的解決方案。jquery展開崩潰效率

的代碼如下:

function hide(boxtohide, boxtomodify, expandbox) { 

$('#' + boxtohide).hide(300); 
$('#' + boxtomodify).css('background-image', 'url("images/new/date.png")'); 
$('#' + boxtomodify).css('height', '69px'); 
$('#' + expandbox).show(300); 

} 

function show(boxtohide, boxtomodify, expandbox, origheight, origurl) { 
$('#' + expandbox).hide(300); 
$('#' + boxtomodify).css('height', origheight); 
$('#' + boxtomodify).css('background-image', 'url("'+origurl+'")'); 
$('#' + boxtohide).show(300); 


} 

背後的邏輯是這樣的:

  • 用戶點擊隱藏
  • 內容被隱藏
  • 內容封裝器被替換爲薄的div
  • 展開按鈕顯示在內容包裝(即它取代原來的內容)

並反向再次擴大。

對我來說,代碼只是感覺有點笨拙,我不是一個JavaScript專家,所以也許這裏有點深度,歡迎任何建議!

戴夫

+0

我們展示你的HTML。 – Shmiddty

+1

你可能會考慮http://codereview.stackexchange.com –

回答

1

唯一明顯的變化,我建議是$('#' + boxtomodify')線,可以壓縮到:

function hide(boxtohide, boxtomodify, expandbox) { 
    $('#' + boxtohide).hide(300); 
    $('#' + boxtomodify).css({ 
     'background-image' : 'url("images/new/date.png")'), 
     'height' : '69px' }); 
    $('#' + expandbox).show(300); 
} 

function show(boxtohide, boxtomodify, expandbox, origheight, origurl) { 
    $('#' + expandbox).hide(300); 
    $('#' + boxtomodify).css({ 
     'height' : origheight 
     'background-image' : 'url("'+origurl+'")' }); 
    $('#' + boxtohide).show(300); 
} 
1

你可以加快代碼只是在JS首先得到每一個元素,並連鎖的CSS修改,具體如下:

function hide(boxtohide, boxtomodify, expandbox) { 

var hideElem = document.getElementById(boxtohide), 
    modElem = document.getElementById(boxtomodify), 
    expandElem = document.getElementById(expandbox), 
    cssObj = { 'background-image' : 'url("images/new/date.png")', 
       'height' : '69px' }; 

$(hideElem).hide(300); 
$(modElem).css(cssObj); 
$(expandElem).show(300); 

} 
+0

不錯,也會實現這個 - 謝謝:) – swiss196

1

我敢打賭,你正在接近這樣太複雜了,使用jQuery你可以做這樣的事情用最少的代碼,例如:

jsfiddle

$('.toggle').on('click', 'h3', function() { 
    var $content = $(this).next('.content'); 
    $content.slideToggle('fast'); 
}); 
+0

好方法,之前沒有見過.next(),我想我可以實現這個。我會盡快給您回覆! – swiss196