js实现滚轮改变元素的高度

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body style="height: 2000px;">
    <div style="width: 100px;height: 100px;background: red;position: absolute;"></div>
    </body>
    <script>
        //获取div
        var div = document.querySelector('div');
        div.onmousewheel = function(e){
            var ev = window.event || e;
			console.log(div.clientHeight);
            //获取事件对象的 wheelDelta属性  监听滚轮滚动方向
            if(ev.wheelDelta>0){
                //向上滚动  让div高度减小 10px
                var h = div.clientHeight;
                h-=10;
                div.style.height = h+'px';
            }else{
                //向下滚动  让div高度增大 10px
                var h = div.clientHeight;
                h+=10;
                div.style.height = h+'px';
                //阻止默认行为
                return false;
            }
        }
        if(div.addEventListener!=undefined){
            div.addEventListener('DOMMouseScroll',function(e){
                var ev = window.event || e;
				if(ev.detail<0){
				    //向上滚动  让div高度减小 10px
				    var h = div.clientHeight;
				    h-=10;
				    div.style.height = h+'px';
				}else{
				    //向下滚动  让div高度增大 10px
				    var h = div.clientHeight;
				    h+=10;
				    div.style.height = h+'px';
				    //阻止默认行为
				    ev.preventDefault();
				}
            }) 
        }
    </script>
</html>

 

posted @ 2020-04-08 21:32  JackieDYH  阅读(21)  评论(0编辑  收藏  举报  来源