当前位置:首页 > 软件编程开发 > 正文

【教程】jquery换图技巧,超详细

【教程】jquery换图技巧,超详细

【教程】jquery换图技巧,超详细 jquery是前端开发常用的框架,其中换图技巧更是应用广泛。在本篇教程中,我们将介绍jquery里怎样换图,让你的网站更加生动...

【教程】jquery换图技巧,超详细
jquery是前端开发常用的框架,其中换图技巧更是应用广泛。在本篇教程中,我们将介绍jquery里怎样换图,让你的网站更加生动有趣。
一、准备工作
在jquery中,我们可以使用$(\"#id\").attr(\"src\",\"newimage.jpg\")这个函数来改变图片的src属性值。为了更好地展现新图片,我们需要提前准备好多张不同大小、不同形状的图片。
二、基础换图
基础换图指的是直接通过jquery改变图片的src属性值。我们可以为图片添加一个事件,当鼠标移到图片上时,更换成不同的图片。代码实现如下:
$(\"#img\").hover(function(){
$(this).attr(\"src\",\"newimage.jpg\");
},function(){
$(this).attr(\"src\",\"oldimage.jpg\");
});
三、渐变换图
渐变换图指的是通过动画效果来改变图片。我们可以设置图片的不透明度为0,然后通过动画将其渐变为1,实现图片逐渐显示的效果。代码实现如下:
$(\"#img\").hover(function(){
$(this).stop().animate({\"opacity\":\"0\"},\"fast\");
$(this).attr(\"src\",\"newimage.jpg\");
$(this).stop().animate({\"opacity\":\"1\"},\"fast\");
},function(){
$(this).stop().animate({\"opacity\":\"0\"},\"fast\");
$(this).attr(\"src\",\"oldimage.jpg\");
$(this).stop().animate({\"opacity\":\"1\"},\"fast\");
});
四、滑动换图
滑动换图指的是通过动画效果,将新旧图片同时展现在页面上,并通过动画将旧图片滑动出去,新图片滑动进入,实现图片的更换效果。代码实现如下:
$(\"#img\").hover(function(){
//创建新图片并将其添加到页面上
var $newimg = $('').hide().appendTo(\"#container\");
//将新旧图片的位置调整到相同的位置
$newimg.css({\"position\":\"absolute\",\"top\":$(this).position().top,\"left\":$(this).position().left});
//滑动新旧图片
$(this).stop().animate({left:\"+=100px\"},\"fast\",function(){
$(this).hide().css({\"left\":\"0\"}).attr(\"src\",\"newimage.jpg\").fadeIn(\"fast\");
});
$newimg.stop().animate({left:\"+=100px\"},\"fast\",function(){
$(this).css({\"left\":\"0\"}).fadeIn(\"fast\");
});
},function(){
//创建旧图片并将其添加到页面上
var $oldimg = $('').hide().appendTo(\"#container\");
//将新旧图片的位置调整到相同的位置
$oldimg.css({\"position\":\"absolute\",\"top\":$(this).position().top,\"left\":$(this).position().left});
$(this).hide();
//滑动新旧图片
$oldimg.stop().animate({left:\"+=100px\"},\"fast\",function(){
$(this).css({\"left\":\"0\"}).fadeIn(\"fast\");
});
});
通过以上几种方法,我们可以轻松实现jquery中的换图效果。希望本篇教程对你的前端开发有所帮助。

最新文章