使用jQuery切换宽度
如何使用动画切换div的宽度?
HTML:
CSS:
#toggle{ height:200px; width:200px; background:red; } #toggle-button{ height:20px; width:20px; background:blue; }
jQuery的:
$(document).ready( function(){ $('#toggle-button').click( function() { $('#toggle').toggle(function() { $('#toggle').animate({width:"200px"}); }, function() { $('#toggle').animate({width:"300px"}); }); }); });
不起作用的示例: http : //jsfiddle.net/ZfHZV/1/
编辑:我的目标是在单击蓝色div时更改宽度
试试这个:
$(document).ready( function(){ $('#toggle-button').click( function() { var toggleWidth = $("#toggle").width() == 300 ? "200px" : "300px"; $('#toggle').animate({ width: toggleWidth }); }); });
示例小提琴
好家伙! 你的代码有效,你只是不明白它的作用……
$('#toggle-button').click( function() { // Execute when the toggle button is clicked. $('#toggle').toggle(function() { // Attach toggle function that fire different // callback when clicked. $('#toggle').animate({width:"200px"}); }, function() { $('#toggle').animate({width:"300px"}); }); });
点击蓝色div,然后点击红色div几次,看看它是如何工作的。
请注意,您最好使用one
而不是click
来附加切换单击回调以避免多次回调点击:
$('#toggle-button').one('click', function() { $('#toggle').toggle(function() { $('#toggle').animate({width:"200px"}); }, function() { $('#toggle').animate({width:"300px"}); }); });
现场演示
有两种叫做toggle
jQuery方法。 一个切换可见性,这与此无关。 另一个应用单击处理程序,它交替激活函数。 这就是你正在使用的。 但是,你错了。
您实际在做的是等待单击#toggle-button
,然后将单击处理程序绑定到#toggle
。 因此,在第一次单击#toggle-button
后单击#toggle
,就会出现动画。 (多次点击#toggle-button
后情况会变得更复杂。
您想直接在#toggle-button
上使用toggle
:
$('#toggle-button').toggle(function() { //fired the first time $('#toggle').animate({width:"200px"}); }, function() { // fired the second time $('#toggle').animate({width:"300px"}); });
工作代码 (自从你从200px开始,第一次点击似乎什么都不做)
试试这个:它适用于所有版本的Jquery || jquery 1.10.1 || 到|| jquery 2.1.4 ||
脚本
$(document).ready( function(){ $('#toggle-button').click( function() { var toggleWidth = $("#toggle").width() == 800 ? "0px" : "800px"; $('#toggle').animate({ width: toggleWidth }); }); });
#toggle{ height:200px; width:0px; background:red; }
Toggle Width with jQuery
使用JQuery 2.1.1并使用CSS设置宽度和过渡。 也适用于百分比宽度,颜色变化等。
$('#button-enlarge').on('click', function () { $('.box').toggleClass('expanded'); });
.box.expanded { background-color: #e99; transition: all .3s; width: 100%; } .box { width: 40%; transition: all .3s; background-color: #f00; color: #fff; height: 140px; } #button-enlarge { padding: 10px 15px; border: 1px solid #999; display: inline-block; }
box
$('#toggle-button').one('click', function() { $('#toggle').animate({ width: 'toggle'}, 1000); });
此切换0到您定义的宽度
我试过这个并且工作
$("#searchIcon").click(function(){ var toggleWidth = "0px"; if($("#searchbox").width() == 118) { toggleWidth="0px"; } else { toggleWidth="120px"; } $('#searchbox').animate({ width: toggleWidth });
});