欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

JavaScript笔记之处理图像

程序员文章站 2022-05-10 23:45:44
...
JavaScript最常见也最显著的用途之一是在网页上添加动画,从而在视觉上更具有吸引力。其中有翻转器效果,广告条应用。记录两个实用的示例:
(一)在循环广告条中添加链接
这样可以让访问者通过点击链接进入与广告相关的站点。
广告条所需的HTML
[html]
<!-- 在循环广告中添加链接 -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotating Banner with Links</title>
<script type="text/javascript" src="script01.js"></script>
</head>
<body bgcolor="#FFFFFF">
<div align="center">
<a href="http://www.php1.cn/"> </div>
</body>
</html>

以下的js脚本(script01.js)演示如何将循环广告条转换为真正的可点击的广告条
[javascript]
window.onload = initBannerLink;

var thisAd = 0;

function initBannerLink() {
if (document.getElementById("adBanner").parentNode.tagName == "A") {
document.getElementById("adBanner").parentNode.onclick = newLocation;
}
//检查adBanner对象是否包围在链接标签中,如果是这样,那么当点击链接时,将调用newLocation()函数.
rotate();
}

function newLocation() {
var adURL = new Array("negrino.com","sun.com","microsoft.com");
document.location.href = "http://www." + adURL[thisAd];//将当前文档窗口设置为文本字符串<a href="http://www.php1.cn/">http://www">http://www.加上adURL的</a>的值 return false;//告诉浏览器不要再加载这个href,否则会加载URL两次
}

function rotate() {
var adImages = new Array("images/banner1.gif","images/banner2.gif","images/banner3.gif");

thisAd++;
if (thisAd == adImages.length) {
thisAd = 0;
}
document.getElementById("adBanner").src = adImages[thisAd];

setTimeout(rotate, 3 * 1000);
}
注意:adURL数组中的成员数量必须与adImages数组相同,这个脚本才能正常工作
建一个images文件夹,然后存入banner1.gif,banner2.gif,banner3.gif三张gif格式图片

(二)随机开始循环显示图像
如果有很多图片需要显示,可能不希望在每次加载页面时都从同样的图像开始显示,下面HTML和js组合可以实现随机开始
[html]
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotating Random Banner</title>
<script type="text/javascript" src="script02.js"></script>
</head>
<body bgcolor="#FFFFFF">
<div align="center">
<img src="images/spacer.gif" width="400" height="75" id="adBanner" alt="Ad Banner" />
</div>
</body>
</html>

以下js脚本(script02.js)可以从一个随机图像开始显示图像
[javascript]
window.onload = choosePic;

var adImages = new Array("images/reading1.gif","images/reading2.gif","images/reading3.gif");
var thisAd = 0;

function choosePic() {
thisAd = Math.floor((Math.random() * adImages.length));
document.getElementById("adBanner").src = adImages[thisAd];

rotate();
}

function rotate() {
thisAd++;
if (thisAd == adImages.length) {
thisAd = 0;
}
document.getElementById("adBanner").src = adImages[thisAd];

setTimeout(rotate, 3 * 1000);
}

相关标签: JavaScript