2012-03-06 29 views
0

我希望在單擊時動態調整元素的大小,並能夠在第二次單擊時恢復其原始大小。我想toggleClass可以做的工作,但顯然事實並非如此:如何激活/禁用動態調整大小的元素

$(document).ready(function() { 
$(this).click(function() { 
    var new_size = // dynamically calculated value; 
    $('.resize').css({'width': new_size, 'height': new_size}); 
    $(this).toggleClass('resize'); 
}); 
}); 

是否有一個簡單的方法來解決此問題?

+0

' toggleClass'是這個簡單的方法。 – Starx 2012-03-06 07:04:28

+0

如果toggleclass不工作可能你的css規則對於那個類不夠具體 – charlietfl 2012-03-06 07:12:39

+0

@charlietfl:我如何使它更具體? – 2012-03-06 07:15:22

回答

2

這行代碼:

$('.resize').css({'width': new_size, 'height': new_size}); 

是不是做你認爲它是。爲了讓對象在添加類時更改大小,您需要一個實際的CSS規則,該規則指定.resize類,該規則不適用於動態計算的大小。

這行代碼只是用.resize類設置任何對象的高度和寬度,並且沒有爲沒有該類的對象做任何事情。因此,你可以調整一次對象的大小(當它有這個類時)並且再也不會改變它的大小。它不會切換任何東西。

我建議你保存舊的尺寸,然後你可以在需要時恢復它,並保存切換值。 jQuery的。數據()函數工作得很好保存此類信息的:

$(document).ready(function() { 
     $(this).click(function() { 
     var this$ = $(this); 
     // if it's currently at the dynamic size, restore the original size 
     if (this$.data("dynamicallySized")) { 
      $(this.css(this$.data("origSize")) 
       .data("dynamicallySized", false); // set flag that we're not dynamic 
     } else { 
      // save original size 
      this$.data("origSize", {height: this$.height(), width: this$.width()}) 
       .css(new_size) 
       .data(dynamicallySized", true); // set flag that we're dynamically sized 
     } 
     }); 
}); 
+0

感謝您的解釋,它的工作:) – 2012-03-06 07:44:41

+0

我覺得你的解決方案更通用,最終選擇你solarise的,雖然它很難消化。 – 2012-03-07 03:46:13

1

你可以使用jQuery.data()來存儲舊值,準備重新按第二下

$(document).ready(function() { 
$(this).click(function() { 
    if($(this).data("old")){ 
    var old = $(this).data("old"); 
    $(this).css({'width': old, 'height': old}); 
    //clear out the old_size data so it won't execute this next time 
    $(this).removeData("old"); 
    } else { 
    var old = $(this).height(); 
    var new_size = // dynamically calculated value 
    $(this).data("old", old); 
    $(this).css({'width': new_size, 'height': new_size});  
    } 
}); 
}); 
+0

你的風格比較容易閱讀,謝謝:) – 2012-03-06 07:45:54