[英]Javascript: Expanding Boxes Toggle Button
what I am trying to do is an expanding box that expands and retracts with the press of the same button. 我想要做的是一个扩展框,该扩展框可以通过按同一按钮来扩展和收缩。 I have the functions but I'm not sure where to go from here.
我有功能,但是我不确定从这里去哪里。 I need to write some code that let's me run these functions with the same button, retract if it's expanded and vice-versa.
我需要编写一些代码,让我使用相同的按钮运行这些功能,如果扩展则撤消,反之亦然。 How would I go about doing this?
我将如何去做呢?
Here's my functions: 这是我的功能:
function expand(element){
var target = document.getElementById(element);
var h = target.offsetHeight;
var sh = target.scrollHeight;
var loopTimer = setTimeout('expand(\''+element+'\')',8);
if(h < sh){
h += 5;
}
else {
clearTimeout(loopTimer);
}
target.style.height = h+"px";
}
function retract(element){
var target = document.getElementById(element);
var h = target.offsetHeight;
var loopTimer = setTimeout('retract(\''+element+'\')',8);
if(h > 0){
h -= 5;
}
else {
target.style.height = "0px";
clearTimeout(loopTimer);
}
target.style.height = h+"px";
}
And here is the html 这是HTML
<p class="mbars">
<a href="#">Togglebutton 1</a>
</p>
<div id="div1" class="mydivs">
<p>Box 1 Content</p>
<p>Box 1 Content</p>
<p>Box 1 Content</p>
</div>
<p class="mbars">
<a href="#">Togglebutton 2</a>
</p>
<div id="div2" class="mydivs">
<p>Box 2 Content</p>
<p>Box 2 Content</p>
<p>Box 2 Content</p>
<p>Box 2 Content</p>
<p>Box 2 Content</p>
</div>
Very thankful for help! 非常感谢您的帮助!
You could add a function that checks your div height and decides whether to expand or retract accordingly, something similar to: 您可以添加一个函数来检查div高度并决定是否相应地扩展或缩回,类似于:
function toggle(element) {
var target = document.getElementById(element);
var h = target.offsetHeight;
if(h < 5){
expand(element);
} else {
retract(element);
}
}
Combining the answer from ProfessorT, we can tie it all together with a data attribute and an event listener. 结合ProfessorT的答案,我们可以将其与数据属性和事件侦听器结合在一起。
HTML: HTML:
<a href="#" data-toggle-div='div1'>Togglebutton 1</a>
JavaScript: JavaScript的:
function toggle(element) {
var target = document.getElementById(element);
var h = target.offsetHeight;
if(h < 5){
expand(element);
} else {
retract(element);
}
}
document.querySelector('a').addEventListener('click', function (event) {
var id = event.target.getAttribute('data-toggle-div');
toggle(id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.