我正在使用下面的Javascript来制作手风琴的动画(它是这里解释的稍微修改的变体:http://tympanus.net/codrops/2010/04/26/elegant-accordion-with-jquery-and-css3/。
现在我想在页面加载时打开第一个元素,所以我想我只是通过 Javascript 给它某种额外的类(并通过 CSS 定义.active
状态)让它打开。
这有效,但是,如果我将鼠标悬停在除.active
first-element
之外的任何元素上,第一个元素将保持其状态,并保持打开状态,直到我将鼠标悬停在它上面至少一次。
所以,我想要的是:我的手风琴的第一个元素是打开的,如果用户将鼠标悬停在任何不是第一个元素的元素上,则会折叠。我想我需要在 hover
函数中添加一行来将类从第一个元素中带走,或者为新元素提供活动状态,但我不知道该怎么做并不断破坏它。
<script type="text/javascript">
jQuery(function() {
activeItem = jQuery("#accordion li:first");
jQuery(activeItem).addClass('active');
jQuery('#accordion > li, #accordion > li.heading').hover(
function () {
var jQuerythis = jQuery(this);
jQuerythis.stop().animate({'height':'280px'},500);
jQuery('.heading',jQuerythis).stop(true,true).fadeOut();
jQuery('.bgDescription',jQuerythis).stop(true,true).slideDown(500);
jQuery('.description',jQuerythis).stop(true,true).fadeIn();
},
function () {
var jQuerythis = jQuery(this);
jQuerythis.stop().animate({'height':'40px'},1000);
jQuery('.heading',jQuerythis).stop(true,true).fadeIn();
jQuery('.description',jQuerythis).stop(true,true).fadeOut(500);
jQuery('.bgDescription',jQuerythis).stop(true,true).slideUp(700);
}
);
});
</script>
看起来这种情况正在发生,因为每个手风琴项都有自己的悬停事件,该事件负责处理自己的动画。您可以稍微重构代码,使其更易于理解和重用:
var activeItem = jQuery("#accordion li:first");
jQuery('#accordion > li, #accordion > li.heading').hover(
function () { hoverMe(jQuery(this)); },
function () { unhoverMe(jQuery(this)); }
);
//This gets called when cursor hovers over any accordion item
var hoverMe = function(jQuerythis) {
//If the first item is still active
if (activeItem) {
contract(activeItem); //...Shrink it!
activeItem = false;
}
//Expand the accordion item
expand(jQuerythis);
};
//This gets called when cursor moves out of accordion item
var unhoverMe = function(jQuerythis) {
contract(jQuerythis);
};
//I have moved the hover animation out into a separate function, so we can call it on page load
var expand = function(jQuerythis) {
jQuerythis.stop().animate({'height':'280px'},500);
jQuery('.heading',jQuerythis).stop(true,true).fadeOut();
jQuery('.bgDescription',jQuerythis).stop(true,true).slideDown(500);
jQuery('.description',jQuerythis).stop(true,true).fadeIn();
};
//I have moved the unhover animation out into a separate function, so we can contract the first active item from hoverMe()
var contract = function() {
jQuerythis.stop().animate({'height':'40px'},1000);
jQuery('.heading',jQuerythis).stop(true,true).fadeIn();
jQuery('.description',jQuerythis).stop(true,true).fadeOut(500);
jQuery('.bgDescription',jQuerythis).stop(true,true).slideUp(700);
};
//Now expand the first item
expand(activeItem);
我整理了一个简化版本来演示逻辑。请让我知道你过得怎么样。