我有一个现有的功能,当点击导航菜单项时,垂直网站的背景图像会发生变化。
<script type="text/javascript">
$(function() {
$('a.panel-home').click(function(){
$("#bgimg").attr('src',"<?php bloginfo('stylesheet_directory'); ?>/images/bg1.jpg");
return false;
});
});
我无法弄清楚如何将动画绑定到此功能,以便新的背景图像淡入...现在它是一个严酷的瞬间转换。我想要
的效果$("#bgimg").fadeIn(1500);
...但我对javascript / jquery有点新鲜。
答案 0 :(得分:1)
将图片封闭在div
中,然后将效果应用到div
,如下所示:
HTML:
<div><img id="bgimg" src="...."></div>
JAVASCRIPT:
$(function() {
$('a.panel-home').click(function(){
$("#bgimg").parent().fadeOut(1000, function() {
$("#bgimg").attr('src',"<?php bloginfo('stylesheet_directory'); ?>/images/bg1.jpg");
$(this).fadeIn(1000);
});
return false;
});
});
答案 1 :(得分:1)
要同时淡化它们,您可以使用以下代码:
/* This must be called on 'img' tag. Enhanced to support more than one image, first image in options argument,
* rest are in more_images argument, which is string array with following format:
* ["400|1000|apple.png","800|apple2.png", "apple3.png"]
* with 3 elements in pipe separation they are delay|duration|image
* with 2 elements they are duration|image
* and with one element, that's image, the default delay is zero and default duration is 800
*
* Ignore more_images argument if you only want to transition from one image to another one.
* Any external code can check if there's an animation running by checking if the parent div of the img
* being animated has the attribute data-anim . This is useful for external code to check
* if the transitions have ended (in an setinterval call for example)*/
jQuery.fn.transictionto = function(options, more_images) {
var settings = jQuery.extend({
}, options || {});
//wrap into div if no div is present.
$(this).each(function() {
if ($(this).parent('div').length == 0) {
$(this).wrap('<div></div>')
}
//mark to check if animation is in being done
$(this).parent().attr('data-anim','1');
//now swap with background trick
$(this)
.parent()
.css('background-image', 'url(' + settings.destinationImage + ')')
.css('background-repeat', 'no-repeat')
.end()
.fadeOut(settings.duration, function() {
this.src = settings.destinationImage;
$(this).show();
if (more_images != null && more_images.length) {
var im = more_images.shift().split('|');//shift shrinks array
var dly = im.length == 3 ? parseInt(im[0],10) : 0;
var drt = im.length > 1 ? parseInt(im[im.length-2],10) : 800;
$(this).delay(dly).transictionto({ destinationImage: im[im.length-1], duration: drt }, more_images);
} else {
$(this).parent().removeAttr('data-anim');
}
});
});
}
$(function() {
$('a.panel-home').click(function(){
destImage = "<?php bloginfo('stylesheet_directory'); ?>/images/bg1.jpg";
$("#bgimg").transictionto({ destinationImage: destImage, duration: 800 });
return false;
});
});
这次必须在transictionto()
元素上调用img
函数。