我有以下用javascript编写的函数来操作上滑/下滑框。但在Firefox中,它出现故障。它只是打开/关闭一次。之后没有比赛。 我从框中获取height()参数并将其存储在隐藏输入中。但是firefox无法读取盒子的正确高度。
查看代码以便更好地理解:
JS:
function boxCollapse() {
$("#boxHeight").attr("value", parseInt($("#accTipsBox").height()));
$("#accTipsBox").animate({height:'0px'});
$(".btnCollapse").css({display:'none'});
$(".btnExpand").css({display:'block'});
$("#accTipsBox").css({padding:'0px'});
}
function boxExpand() {
$("#accTipsBox").animate({height: $("#boxHeight").attr("value")});
$(".btnExpand").css({display:'none'});
$(".btnCollapse").css({display:'block'});
$("#accTipsBox").css({padding:'0px'});
}
HTML:
<section class="accBox grey">
<header>
<div class="title">DISCLAIMERS</div>
<a style="display: none;" class="btnExpand" href="javascript:void(0);"><img src="/resources/images/boxExpandGrey.jpg" alt="button"></a>
<a style="display: block;" class="btnCollapse" href="javascript:void(0);"><img src="/resources/images/boxCollapseGrey.jpg" alt="button"></a>
</header>
<div id="accTipsBox" style="height: 125px; padding: 0px;">
<input type="hidden" id="boxHeight" value="125">
<div class="accBoxContent">
<div><p></p><p></p><p></p></div>
</div>
</div>
</section>
答案 0 :(得分:2)
我认为这就是你想要的:
//bind a `click` event handler to all the elements with the `btnExpandCollapse` class
$('.btnExpandCollapse').on('click', function (event) {
//stop the default behavior of clicking the link (stop the browser from scrolling to the top of the page)
event.preventDefault();
//first select the parent of this element (`header` tag) and then get its sibling element that has the `accTipsBox` class, then take that element and slide it up or down depending on its current state
$(this).parent().siblings('.accTipsBox').slideToggle(500);
});
对HTML进行一些微调:
<section class="accBox grey">
<header>
<div class="title">DISCLAIMERS</div>
<!-- Notice there is only one link now that does the job of both -->
<a class="btnExpandCollapse" href="#"><img src="/resources/images/boxExpandGrey.jpg" alt="button"></a>
</header>
<!-- Notice I changed the ID attribute to CLASS so this code will work for repeated structure -->
<div class="accTipsBox" style="height: 125px; padding: 0px;">
<div class="accBoxContent">
<div>
<p>1</p>
<p>2</p>
<p>3</p>
</div>
</div>
</div>
</section>
以下是演示:http://jsfiddle.net/VGN64/
以下是一些文档:
.slideToggle()
:http://api.jquery.com/slidetoggle .siblings()
:http://api.jquery.com/siblings 另外,如果要存储有关DOM元素的数据,请使用jQuery的$.data()
方法:
var $box = $("#accTipsBox");
$.data($box[0], 'height', $box.height());
然后,您可以像这样访问此数据
var height = $.data($('#accTipsBox')[0], 'height');
请注意,我将[0]
附加到jQuery对象的末尾以仅返回与该对象关联的DOM节点,这是$.data()
方法所需的:http://api.jquery.com/jquery.data。这是一种非常快速的存储与DOM元素相关的数据的方法。