gpt4 book ai didi

jquery - 自动展开的div

转载 作者:行者123 更新时间:2023-11-28 06:53:27 24 4
gpt4 key购买 nike

我遇到了一个问题。单击时,我正在尝试展开和缩回#inner 的高度。但是,当我这样做时,我希望#container 的高度也增加,但没有像我对#inner (+=65px) 那样指定增加。但是,#container 不会像我想象的那样在设置为“auto”时自动扩展。有人可以帮我解决这个问题吗?非常感谢,提前致谢。

HTML:

<div id=‘container’>
<div id=‘inner’>This is the inner div</div>
</div>

J查询:

 function handler1() {
$(this).css('height', '+=65px');
$(this).one("click", handler2);
}

function handler2() {
$(this).css('height', ' -= 65px ');
$(this).one("click", handler1);
}

$("#inner").one("click", handler1);

CSS:

#container {
display: block;
width: 200px;
height: auto;
}
#inner {
height: auto;
}

最佳答案

你可以大大简化这段代码。我坚持通过 jQuery 添加 css,因为你就是这样做的,但只使用类会更好。还添加了颜色,以便您可以看到更改。与其使用 one 增加不断添加和删除事件的开销,我们可以只使用一个处理程序来跟踪带有类的 div 的状态。

HTML:

<div id="container">
<div id="inner">This is the inner div</div>
</div>

JS:

 function handler1 () {
var inner = $("#inner");
if (!inner.hasClass('added')) {
inner.css('height', '+=65px').addClass('added');
}
else {
inner.css('height', '-=65px').removeClass('added');
}
}

$("#inner").on("click", handler1);

CSS:

#container {
width: 200px;
background: red;
}

#inner {
background: yellow;
}

fiddle :http://jsfiddle.net/4pv6y6as/

关于jquery - 自动展开的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33652980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com