所以我有一个部分,我想在其中单击图像并通过在 上切换类
为高度设置动画以显示 .open
使 .speaker-info
动画打开。 speaker-container.speaker-info
,同时切换类 .hover
以获得悬停状态图像。 .fade
类也会切换到 .speaker-info
以更改不透明度。如果我单击一个图像并在同一位置将其关闭,我一切正常,但是当我打开一个图像并单击另一个图像时,一切都会关闭,因此我需要单击两次才能打开另一个图像,并且悬停图像状态为上一张图片。
所以我想打开一个 div,然后如果单击另一张图片,则全部关闭,然后打开最近的一张。我一直在兜圈子,试图找出最好的方法来做到这一点。但我一直撞墙。
我基本上是通过切换 css 类来创建打开/关闭和悬停来触发所有内容。
这是我的代码。
此外,我正在寻找有关如何使我的代码更灵活、更高效的意见,有时我觉得我写了很多我可以用更少的几行来做同样的事情。
谢谢!
<section id="speakers">
<div class="container">
<div class="row">
<div class='speaker-container'>
<div class="span3 offset1" id="{row_index}">
<div class="speaker-img">
<img src="{speaker_image}" alt="{speaker_name}" class="hover">
<img src="{speaker_hover}" alt="{speaker_name}">
</div>
<h4>{speaker_name}</h4>
</div>
<div class="speaker-info">
<button class="close-speaker">Close</button>
<h3>{speaker_name}{if speaker_title}, {speaker_title}{/if}</h3>
<p>{speaker_bio}</p>
</div>
</div>
</div>
</div>
</section> {!-- /End Speakers --}
Javascript 代码
$('.speaker-container').each(function(){
var containerHeight = $(this).height();
$('.speaker-info').css({ 'top' : containerHeight});
});
$('#speakers .span3').on('click', function(){
var containerHeight = $(this).parent('.speaker-container').height();
var h = $(this).next('.speaker-info').height();
var totalHeight = containerHeight + h;
$(this).find('.speaker-img').children().toggleClass('hover');
$('#speakers .span3').not($(this).next('.speaker-info')).next('.speaker-info').removeClass('fade');
if (!$('.speaker-info').hasClass('fade') && !$('.speaker-container').hasClass('open')) {
$(this).closest('.speaker-container').css({'height' : totalHeight}).addClass('open');
$(this).next('.speaker-info').addClass('fade');
} else {
$('.speaker-container').css({'height' : h}).removeClass('open');
$(this).next('.speaker-info').toggleClass('fade');
$('.speaker-info').removeClass('fade');
}
});
$('.close-speaker').on('click', function() {
var container = $(this).closest('.speaker-info').height();
$(this).closest('.speaker-container').css({'height' : container}).removeClass('open');
$('.speaker-info').removeClass('fade');
});
最佳答案
我建议您可以将 JQuery 用于您想要实现的功能。这是供您引用的链接:JQuery Accordion .我希望它有所帮助。谢谢!
关于javascript - 打开div并关闭其他,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18980005/