Mouse Scroll Event Up/Down Example in JavaScript

文章源自:http://viralpatel.net/blogs/javascript-mouse-scroll-event-down-example/

Mouse Scroll Event Up/Down Example in JavaScript

The other day I was working on an App that required Google Map like functionality where Mouse Scroll event on an object triggered some action in JavaScript.

Handling Mouse Wheel in JavaScript is quite simple. Most of the browsers support Mouse Scroll Event in one or other way. Mozilla provides window.addEventListener method that can be used to hook a handler for mouse scroll event. Internet Explorer and Opera on the other hand provides document.onmousewheel handler to hook the mouse event.

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:

<html>
<head>
<title>Mouse Scroll Wheel example in JavaScript - ViralPatel.net</title>
<style>
#scroll {
    width: 250px;
    height: 50px;
    border: 2px solid black;
    background-color: lightyellow;
    top: 100px;
    left: 50px;
    position:absolute;
}
</style>
<script language="javascript">
window.onload = function()
{
    //adding the event listerner for Mozilla
    if(window.addEventListener)
        document.addEventListener('DOMMouseScroll', moveObject, false);
 
    //for IE/OPERA etc
    document.onmousewheel = moveObject;
}
function moveObject(event)
{
    var delta = 0;
 
    if (!event) event = window.event;
 
    // normalize the delta
    if (event.wheelDelta) {
 
        // IE and Opera
        delta = event.wheelDelta / 60;
 
    } else if (event.detail) {
 
        // W3C
        delta = -event.detail / 2;
    }
 
    var currPos=document.getElementById('scroll').offsetTop;
 
    //calculating the next position of the object
    currPos=parseInt(currPos)-(delta*10);
 
    //moving the position of the object
    document.getElementById('scroll').style.top = currPos+"px";
    document.getElementById('scroll').innerHTML = event.wheelDelta + ":" + event.detail;
}
</script>
</head>
<body>
Scroll mouse wheel to move this DIV up and down.
    <div id="scroll">Dancing Div</div>
</body>
</html>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值