2012-03-06 52 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