我用javascript编写了以下函数,用于操作幻灯片上下框。但在firefox中,它会出现故障。它只打开/关闭一次。之后就没有戏了。我从框中获取高度()参数,并将其存储在隐藏输入中。但是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>
我想这就是你想要的:
//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
$.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元素相关的数据的方法。