Mouse Scroll Event Up/Down Example in JavaScript

本文介绍了一个使用JavaScript处理鼠标滚轮事件的例子。通过该示例,一个小的DIV元素可以根据鼠标滚轮的滚动方向上下移动。代码适用于多种浏览器,包括IE、Firefox等。

 

Source Code

Let us see an example for catching mouse scroll wheel event in JavaScript. In our example we will have a small DIV that moves up and down on scroll of mouse wheel. Following is the source code of our example:

01<html>
02<head>
03<title>Mouse Scroll Wheel example in JavaScript - ViralPatel.net</title>
04<style>
05#scroll {
06    width: 250px;
07    height: 50px;
08    border: 2px solid black;
09    background-color: lightyellow;
10    top: 100px;
11    left: 50px;
12    position:absolute;
13}
14</style>
15<script language="javascript">
16window.onload = function()
17{
18    //adding the event listerner for Mozilla
19    if(window.addEventListener)
20        document.addEventListener('DOMMouseScroll', moveObject, false);
21  
22    //for IE/OPERA etc
23    document.onmousewheel = moveObject;
24}
25function moveObject(event)
26{
27    var delta = 0;
28  
29    if (!event) event = window.event;
30  
31    // normalize the delta
32    if (event.wheelDelta) {
33  
34        // IE and Opera
35        delta = event.wheelDelta / 60;
36  
37    } else if (event.detail) {
38  
39        // W3C
40        delta = -event.detail / 2;
41    }
42  
43    var currPos=document.getElementById('scroll').offsetTop;
44  
45    //calculating the next position of the object
46    currPos=parseInt(currPos)-(delta*10);
47  
48    //moving the position of the object
49    document.getElementById('scroll').style.top = currPos+"px";
50    document.getElementById('scroll').innerHTML = event.wheelDelta + ":" + event.detail;
51}
52</script>
53</head>
54<body>
55Scroll mouse wheel to move this DIV up and down.
56    <div id="scroll">Dancing Div</div>
57</body>
58</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值