最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
javascript滚轮事件基础实例讲解(37)
时间:2017-04-06 编辑:简简单单 来源:一聚教程网
代码如下 | 复制代码 |
#box1{ width: 100px; height: 100px; background-color: red; }
window.onload = function(){
//使div可以跟随鼠标滚轮滚动来改变高度 //滚轮向下滚,div变高 滚轮向上滚 div变短
//获取box1 var box1 = document.getElementById("box1");
/* * onmousewheel * - 鼠标滚轮滚动的事件,但是该事件火狐浏览器并不支持 * - 在火狐中需要使用DOMMouseScroll,这个事件只能通过addEventListener()来绑定 */ //为box1绑定一个鼠标滚轮滚动的事件 box1.onmousewheel = function(event){ event = event || window.event;
//判断滚轮滚动的方向 /* * wheelDelta * - 事件对象中的属性,可以用来判断鼠标滚轮滚动的方向 * - 向下滚 -120 向上滚 +120 * - 该属性的值并不重要,重要的是值的符号,需要通过符号来判断滚动的方向 * - 但是该属性火狐浏览器并不支持 */ //alert(event.wheelDelta);
/* * 火狐中通过detail来判断方向 * - 向上滚 -3 向下滚 +3 */ //alert(event.detail);
if(event.wheelDelta <0|| event.detail > 0){ //向下滚 //增加box1的高度 box1.style.height = box1.offsetHeight + 10 + "px";
}else{ //向上滚 //减小box1的高度 box1.style.height = box1.offsetHeight - 10 + "px"; }
/* * 使用addEventListener()绑定的事件,不能通过return false来取消默认行为 * 需要调用事件对象 preventDefault()方法来取消默认行为 * 但是在IE8中没有该方法 */ event.preventDefault && event.preventDefault();
//当页面中有滚动条时,由于滚轮滚动的默认行为会导致页面整体下移 //取消默认行为 return false;
};
bind(box1 , "DOMMouseScroll" , box1.onmousewheel);
};
function bind(obj , eventStr , callback){
if(obj.addEventListener){ //如果是正常浏览器 obj.addEventListener(eventStr , callback , false); }else{ //IE8 obj.attachEvent("on"+eventStr , function(){ callback.call(obj); }); } }
|