我正在使用下面的Javascript为手风琴制作动画(这是在此处解释的手风琴的略微修改形式:http : //tympanus.net/codrops/2010/04/26/elegant-accordion-with-jquery-and-css3/。
现在,我想在页面加载时打开第一个元素,因此我想我只是通过Javascript为其提供了一些额外的类(并.active
通过CSS定义了该状态)以将其打开。
这行得通,但是,如果我将鼠标悬停在除了first-element
带有所说.active
类的任何类之外,第一个元素将保持其状态,并保持打开状态,直到我至少将鼠标悬停在它之上一次。
所以,我想要的是:我的手风琴的第一个元素是打开的,如果用户将鼠标悬停在不是第一个元素上的任何元素上,它就会折叠。我想我需要在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);
我整理了一个简化的版本来说明逻辑。请让我知道你过得如何。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句