- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
-
<html xmlns="">
-
<head>
-
<title> ImageZoom </title>
-
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-
</head>
-
<body>
-
<img src="3.jpg" id="photo"/>
-
<script>
-
/*!
-
ImageZoom
-
*/
-
var ImageZoom = function() {
-
var Event = {}, ua = navigator.userAgent, isIE = /msie/i.test(ua), isFF = /firefox/i.test(ua);
-
var zoom = 100, min = 50, o = document.getElementById('photo'), w = o.offsetWidth, h = o.offsetHeight;
-
Event.addEvent = function(obj, type, fn) { window.addEventListener ? obj.addEventListener(type, fn, false) : obj.attachEvent('on'+type, fn); };
-
Event.format = function(event) {
-
if(isIE) event.preventDefault = function() { event.returnValue = false };
-
event.data = event.wheelDelta || -event.detail*40;
-
return event;
-
}
-
function ZOom(event) {
-
var e = Event.format(event);
-
zoom += e.data / 12;
-
if(zoom > min) {
-
if(isIE) {
-
o.style.zoom = zoom + '%';
-
} else {
-
o.style.width = w * zoom / 100 + 'px';
-
o.style.height = h * zoom / 100 + 'px';
-
}
-
e.preventDefault();
-
}
-
}
-
return {
-
init: function() {
-
Event.addEvent(o, isFF? 'DOMMouseScroll' : 'mousewheel', ZOom);
-
}
-
}
-
}();
-
-
ImageZoom.init();
-
</script>
-
</body>
-
</html>
主要是滚轮鼠标的兼容性:
1. 绑定滚轮事件. 这次只有FF浏览器特殊用DOMMouseScroll 其余浏览器使用onmousewheel. 代码可以写为:
Event.addEvent(o, isFF? 'DOMMouseScroll' : 'mousewheel', ZOom); |
2. 控制滚轮数值大小和方向. 仅有FF使用 detail 其它的都用wheelDelta. detail每次滚动的值为加减3 而wheelDelta为加减120. 且两者加减针对的方向正好相反.
event.data = event.wheelDelta || -event.detail*40;