Javascript 用一个按钮扩展和减小Div的高度
我目前正试图通过单击一个按钮来扩展div的大小,然后在单击的同时将其减小为0。我尝试了一些方法,但我将最近的一次尝试放在了这个JSFIDLE中。有人能告诉我为什么div既不膨胀也不收缩的方向吗 下面是最近尝试的代码以及CSS和HTMLJavascript 用一个按钮扩展和减小Div的高度,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我目前正试图通过单击一个按钮来扩展div的大小,然后在单击的同时将其减小为0。我尝试了一些方法,但我将最近的一次尝试放在了这个JSFIDLE中。有人能告诉我为什么div既不膨胀也不收缩的方向吗 下面是最近尝试的代码以及CSS和HTML $("dasButton").toggle(function(){ $("#div1").height($("#div1").height()+200); },function(){ $("#div1").height($("#div1").height()-20
$("dasButton").toggle(function(){
$("#div1").height($("#div1").height()+200);
},function(){
$("#div1").height($("#div1").height()-200);
});
});
CSS
HTML
显示:块;
高度:0px;
溢出:隐藏;
边框:1px实心#000;
}
已从jQuery 1.9中删除.toggle()
事件。但是,如果您使用较旧的版本并修复jQuery错误,它可以正常工作:
$("#dasButton").toggle(function () {
$("#div1").height($("#div1").height() + 200);
}, function () {
$("#div1").height($("#div1").height() - 200);
});
我改变你的密码
jQuery:
$("#dasButton").click(function(){
var inputValue=$("#dasButton").attr('value');
if(inputValue=="Expand")
{
$("#div1").animate({height:"200px"});
$("#dasButton").attr('value','Reduce');
}
else if(inputValue=="Reduce")
{
$("#div1").animate({height:"0px"});
$("#dasButton").attr('value','Expand');
}
});
<input type="submit" class="toggle_div" id="dasButton" value="Expand"/><br>
<div id="div1">
HTML:
$("#dasButton").click(function(){
var inputValue=$("#dasButton").attr('value');
if(inputValue=="Expand")
{
$("#div1").animate({height:"200px"});
$("#dasButton").attr('value','Reduce');
}
else if(inputValue=="Reduce")
{
$("#div1").animate({height:"0px"});
$("#dasButton").attr('value','Expand');
}
});
<input type="submit" class="toggle_div" id="dasButton" value="Expand"/><br>
<div id="div1">
toggle()函数不允许在其中编写函数,它只需要速度(int) 也许你可以写这样的东西
$("#dasButton").click(function (e) {
var wdth = $("#div1").width();
if (wdth > 0) {
$("#div1").width(0);
$("#div1").height(0);
}
else {
$("#div1").width(200);
$("#div1").height(200);
}
});
小巧精确:
$("input").click(function () {
var div = $("#div1");
div.height(div.height()==200 ? 0 : 200);
})