用js实现。点击图片的左边,去上一张;点击图片的右边,去下一张。/*** SuperImage.js: 给<img>标签添加其新的属性和事件。* 这个模块会...
用js实现。点击图片的左边,去上一张;点击图片的右边,去下一张。
/**
* SuperImage.js: 给<img>标签添加其新的属性和事件。
* 这个模块会在文档中,寻找所有的含有onclickleft/onclickright/leftcursor/
* rightcursor/lefttitle/righttitle的<img>元素。在图形上面绘制2个透明层,鼠标滑过
* 图片左右部分时,会显示 * lefttitle/righttitle信息同时鼠标样式变为leftcursor/
* rightcursor;点击图片左右时,分别触发onclickleft/onclickright的事件。
*
* 使用示例:
* <img id="imgZone" src="1.jpg"
* onclickleft="prev();"onclickright="next();"
* leftcursor="url(prev.ani)" rightcursor="url(next.ani)"
* lefttitle="点击去上一张" righttitle="点击去下一张" />
*
* 这段代码没有定义任何的全局变量。但是这段代码用到了tool.js中的函数。
*/
(function(){ // 整个模块定义在一个匿名函数中
// 当文档加载完毕调用此函数
if (window.addEventListener)
window.addEventListener("load", init, false);
else
if (window.attachEvent)
window.attachEvent("onload", init);
// 寻找所有的符合条件的img标签
function init(){
var imgtags = document.getElementsByTagName("img");
for (var i = 0; i < imgtags.length; i++) { // 遍历所有标签
var tag = imgtags[i];
var leftcursor = tag.getAttribute("leftcursor");
if (!leftcursor)
continue; // 必须有leftcursor属性
// 向img标签注册事件处理函数
if (tag.addEventListener) {
tag.addEventListener("mousemove", mouseMoveHandler, false);
tag.addEventListener("click", clickHandler, false);
}
else {
tag.onmousemove = mouseMoveHandler;
tag.onclick = clickHandler;
}
}
}
// This is the keypress handler that filters the user's input
function mouseMoveHandler(event){
// Get the event object and character code in a portable way
var e = event || window.event; // Key event object
var p = Tool.getEventOffset(e);
var s = e.srcElement || e.target;
if(p.x>s.width/2){
s.style.cursor = s.getAttribute("rightcursor");
s.title = s.getAttribute("righttitle");
}else{
s.style.cursor = s.getAttribute("leftcursor");
s.title = s.getAttribute("lefttitle");
}
}
function clickHandler(event){
var e = event || window.event; // Key event object
var p = Tool.getEventOffset(e);
var s = e.srcElement || e.target;
if(p.x>s.width/2){
eval(s.getAttribute("onclickright"));
}else{
eval(s.getAttribute("onclickleft"));
}
}
})(); // Finish anonymous function and invoke it.
心得:
1.上面的这种js的写法是一种不干扰的js写法,它不会跟其他的任何未知js冲突。因为在这段代码里面,没有定义任何全局变量,就连主函数也是采用匿名方式定义的,因而避开了产生全局变量的可能。
2.这种封装方式非常不错。使用者只需要包含js,然后就可以在任意的img标签上使用新增的属性,的事件处理函数。