首先
我会推荐你到JQuery Animate documentation。
更具体地说,看看他们是如何制作动画队列的。
$('#clickme').click(function() {
$('#book').animate({
width: 'toggle',
height: 'toggle'
}, {
duration: 5000,
specialEasing: {
width: 'linear',
height: 'easeOutBounce'
},
complete: function() {
$(this).after('<div>Animation complete.</div>');
}
});
});
动画完成后,就是你要添加文字的地方。
解决方案
Here is a JSFiddle of a working solution.
$('.projectContact').mouseenter(function() {
$(this).animate({
width: "95px"
}, 250, function(){
$(this).text('Request a quote')
});
}).mouseleave(function(){
$(this).animate({
width: "16px"
}, 250, function(){
$(this).html("<img src=\"images/mail.png\">");
});
});
我使用了mouseenter 和mouseleave,因为它们不仅更可靠,而且更易于阅读。如您所见,.animate 中的最后一个函数参数(动画完成)是您希望发生更改的位置。
此外,您可以将其添加到元素的样式属性中,您基本上可以强制文本保持在一行,并隐藏超出范围的所有内容。这样,当您制作动画时,文本不会影响容器。
CSS:
.myButton{
white-space: nowrap;
overflow: hidden;
}
如果您不希望 CSS 干扰 CSS 的其余部分,您还可以创建一个包含 CSS 的类,然后在每个动画的开始/结束处添加/删除。
最终解决方案
好的,here is the final solution,有淡入淡出和一切。它不完整,但你明白了。
var current_element = "img";
$('.projectContact').mouseenter(function() {
var par = $(this);
$('.projectContact '+current_element).animate({
opacity: 0
}, 250, function(){
par.animate({
width: "95px"
}, 250, function(){
par.html('<div>Request a quote</div>');
current_element = "div";
});
});
inside = true;
}).mouseleave(function(){
var par = $(this);
$('.projectContact '+current_element).animate({
opacity: 0
}, 250, function(){
par.animate({
width: "16px"
}, 250, function(){
par.html('<img src="http://www.hager.se/icons/icon_mail.gif">');
current_element = "img";
});
});
});
你可以乱用动画时间,但基本上你就是这样做的。我必须在您的“请求报价”文本中添加一个“div”,以便能够单独对其进行动画处理。这样,您也可以使用它的不透明度。
祝你好运!
替代解决方案
Here's a different approach 在您开始制作动画的瞬间编辑元素的文本/图像。这是您当前使用的方法。请注意,CSS white-space: nowrap; 是必需的,这样才能在不使动画“丑陋”的情况下工作。
$('.projectContact').mouseenter(function() {
$(this).animate({
width: "95px"
}, 250).text('Request a quote');
}).mouseleave(function(){
$(this).animate({
width: "16px"
}, 250).html("<img src=\"images/mail.png\">");
});
整理思路
最好使用.clearQueue,这样您的动画就不会开始堆积。它重置动画队列并停止动画,因此,在这种情况下,如果用户快速进出鼠标,动画将直接转到mouseleave 动画。
这也特别有用,例如,当用户在第一个动画序列完成之前将鼠标悬停在元素内外两次或更多次时,它可以防止动画堆积。
See it in use
$('.projectContact').mouseenter(function() {
$(this).animate({
width: "95px"
}, 250).text('Request a quote').clearQueue();
}).mouseleave(function(){
$(this).animate({
width: "16px"
}, 250).html("<img src=\"images/mail.png\">").clearQueue();
});
您也可以使用.stop,它做同样的事情,但只适用于当前动画,而不是整个动画队列。