Dreamweaver当中有一个Rollover Image效果,一般翻译为即鼠标经过图像。这个效果是指当鼠标指针经过一幅图像时,图像的显示会切换为另一幅表示鼠标经过状态的图像;在图像上单击时,会切换为另一幅表示按下状态的图像。在Dreamweaver中实现该效果的脚本比较复杂,接下来使用不唐突的方式来实现该效果。
首先看下实现的结果:
查看演示
接下来是实现基本的XHTML页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Multi State Anchor Example</title> <link rel="stylesheet" href="style.css" type="text/css" media="screen" /> <script src="../../ADS-final-verbose.js" type="text/javascript"></script> <script src="unobtrusiveRollovers.js" type="text/javascript"></script> </head> <body> <h1>Rollover Image</h1> <div> <a href="http://www.everyinch.net/" class="rollover"> <img src="images/button1.png" width="113" height="67" alt="Button 1" /> </a> <a href="http://www.everyinch.net/" class="rollover"> <img src="images/button2.png" width="113" height="67" alt="Button 2" /> </a> </div> </body> </html>
为了实现指定的效果,需要做两项准备工作:
1. 在图片文件名中添加-over和-down,用来表示mouseover和mousedown这两个状态
2. 在XHTML代码的相应链接处,添加class=”rollover”
JavaScript脚本如下:
function registerAnchorListeners(anchor,anchorImage,path,extension) {
// 加载over状态的图片
var imageMouseOver = new Image()
imageMouseOver.src = path + ‘-over’ + extension;
// 当mouseover事件触发时,切换到over状态的图片
ADS.addEvent(anchor, ‘mouseover’, function (W3CEvent) {
anchorImage.src = imageMouseOver.src;
});
// 当mouseout事件触发时,切换回原始的图片
ADS.addEvent(anchor, ‘mouseout’, function (W3CEvent) {
anchorImage.src = path + extension;
});
// 加载down状态的图片
var imageMouseDown = new Image()
imageMouseDown.src = path + ‘-down’ + extension;
// 当mousedown事件触发时,切换到down状态的图片
ADS.addEvent(anchor, ‘mousedown’, function (W3CEvent) {
anchorImage.src = imageMouseDown.src;
});
// 当mouseup事件触发时,切换回原始的图片
ADS.addEvent(anchor, ‘mouseup’, function (W3CEvent) {
anchorImage.src = path + extension;
});
}
function initRolloverImage(W3CEvent) {
// 茶查找页面中所有的链接
var anchors = ADS.getElementsByClassName(‘rollover’,’a’);
// 遍历链接
for (var i=0; i