JavaScript实现首屏大图后自动收缩为小图的广告特效
作者:小括号时间:2026-10-29 14:37:10浏览:107
本文介绍一种基于JavaScript的图片广告特效,页面加载时先展示大图,随后自动缓慢收缩并切换为小图,始终固定于网页顶部。该效果常见于大型门户网站,通过JS控制图片切换与动画,提升用户体验与广告展示效果。
JavaScript实现首屏大图后自动收缩为小图的广告特效
本文通过一个具体实例,展示了如何使用JavaScript实现一种特殊的广告展示效果:页面加载时先显示大图,随后自动收缩并切换为小图。该方案可供开发者参考与借鉴。
这是一种较为优秀的JavaScript图片动画效果。当用户首次打开网页时,会看到一张占据较大区域的大图,类似遮屏广告的效果。经过短暂停留后,大图会自动缓慢收缩,同时由JavaScript控制替换为小图,并始终固定在网页顶部。这种效果在许多大型门户网站中较为常见,整体视觉体验较为出色。
以下是该特效运行时的界面截图:

在线演示链接如下:
http://demo.jb51.net/js/2015/js-big-to-small-pic-adv-codes/
具体实现代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>先显示大图随后自动收起显示小图的JS广告</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<style type="text/css">
html,body{margin:0;text-align:center;font-size:12px;}
img{border:none}
p{margin:0px}
</style>
<script type="text/javascript">
var showAD = {
curve: function(t, b, c, d, s) {
if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
return c / 2 * ((t -= 2) * t * t + 2) + b
},
fx: function(from, to, playTime, onEnd) {
var Me = this,
who = this.adWrap,
position = 0,
changeVal = to - from,
curve = this.curve;
playTime = playTime / 10;
who.style.overflow = 'hidden';
function _run() {
if (position++<playTime) {
who.style.height = Math.max(1, Math.abs(Math.ceil(curve(position, from, changeVal, playTime)))) + "px";
setTimeout(_run, 10)
} else {
onEnd && onEnd.call(Me, to)
}
};
_run()
},
init: function(info) {
var Me = this,
loadImg = new Image;
loadImg.src = info.endImgURL;
window.onload=function() {
Me.endImgURL = info.endImgURL;
Me.img = document.getElementById(info.imgID);
Me.adWrap = document.getElementById(info.adWrapID);
var max = Me.img.height;
setTimeout(function() {
Me.fx(max, 0, 500,
function(x) {
this.img.src = this.endImgURL;
this.curve = function(t, b, c, d) {
if ((t /= d) < (1 / 2.75)) {
return c * (7.5625 * t * t) + b
} else if (t < (2 / 2.75)) {
return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b
} else if (t < (2.5 / 2.75)) {
return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b
} else {
return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b
}
};
this.fx(0, this.img.height,600)
})
},
info.timeout || 1000)
};
}
};
showAD.init({
adWrapID: 'ad_box_2009_06',
imgID: 'adImg',
endImgURL: 'images/as.jpg'
});
</script>
</head>
<body>
<div id="ad_box_2009_06"><img src="images/ab.jpg" id="adImg"></div>
</body>
</html>
希望本文提供的JavaScript程序设计思路对读者有所帮助。
作者最新文章
JS语法错误会阻止加载吗?区分SyntaxError与资源加载失败
2026-11-05 16:08:46
JavaScript常见SyntaxError语法错误排查与修复方法
2026-11-05 13:58:44
JS中slice、substring和substr截取字符串的区别
2026-11-05 13:43:47
JS 转 TS 手动迁移最佳实践:从配置 tsconfig 到消除 any 类型
2026-11-05 11:53:32
为什么JS数组push后得到的是数字而不是数组?
2026-11-05 09:59:18
