当鼠标向下滚动 box1变长; 当滚轮向上滚动时,box1变短

第一步:知道滚轮有没有滚动:鼠标滚轮事件--onwheel--在滚轮滚动时候触发

onmousewheel————在火狐中不支持该属性

火狐需要使用:DOMmouseScroll来绑定滚动事件,注意该事件需要通过addEventListener()函数进行绑定

function bind(obj, eventStr, callback) {

if(obj.addEventListener){

//大部分浏览器

obj.addEventListener(eventStr, callback, false);

}else{

//IE8及以下

obj.attachEvent("on"+eventStr, function(){

callback.call(obj);//this是指定的那个对象

});

}

};

                bind(box1,"DOMMouseScroll",function(){

                        alert('s');

                        });

两个函数进行优化:实现一个函数 

window.onload = function(event) {

var box1 = document.getElementById("box1");

//当鼠标向下滚动 box1变长;

//当滚轮向上滚动时,box1变短onwheel

box1.onmousewheel=function(){

alert('s');

};

bind(box1,"DOMMouseScroll",box1.onmousewheel);

};

alert(event.wheelDelta):鼠标滚轮滚动的方向——不支持火狐

        向上滚动:120

        向下滚动:-120---值不看大小--只看正负

火狐是event.detail

        向上滚动时:-3

        向下滚动 :+3

//当滚轮滚动时,如果浏览器有滚动条,滚动条会随之滚动 //这是浏览器默认行为 可以取消:   return false;

window.onload = function(event) {

var box1 = document.getElementById("box1");

//当鼠标向下滚动 box1变长;

//当滚轮向上滚动时,box1变短onwheel

box1.onmousewheel = function(event) {

//判断鼠标滚轮滚动的方向

//兼容火狐和其他

if (event.wheelDelta > 0 || event.detail < 0) {

//向上滚动 box1变短

box1.style.height = box1.clientHeight - 10 + "px";

} else {

//向下滚动 box1变短

box1.style.height = box1.clientHeight + 10 + "px";

}

//当滚轮滚动时,如果浏览器有滚动条,滚动条会随之滚动

//这是浏览器默认行为 可以取消:

return false;

};

bind(box1, "DOMMouseScroll", box1.onmousewheel);

};

//但是火狐不成功,因为取消默认行为在火狐中使用addEventListener()方法绑定响应函数u,取消默认行为的时候不能使用return false;---需要使用event.preventDefault()取消默认行为

 但是IE8不支持preventDefault

window.onload = function(event) {

var box1 = document.getElementById("box1");

//当鼠标向下滚动 box1变长;

//当滚轮向上滚动时,box1变短onwheel

box1.onmousewheel = function(event) {

//判断鼠标滚轮滚动的方向

//兼容火狐和其他

if (event.wheelDelta > 0 || event.detail < 0) {

//向上滚动 box1变短

box1.style.height = box1.clientHeight - 10 + "px";

} else {

//向下滚动 box1变短

box1.style.height = box1.clientHeight + 10 + "px";

}

//当滚轮滚动时,如果浏览器有滚动条,滚动条会随之滚动

//这是浏览器默认行为 可以取消:

event.preventDefault();

return false;

};

bind(box1, "DOMMouseScroll", box1.onmousewheel);

};

所以需要加判断:

文章链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: