自定义mousewheel事件,实现图片放大缩小功能实现

本文是承接 上一篇的 《自定义鼠标滚动事件》  的基础上实现的,建议大家先看一下上一篇的mousewheel的实现,再浏览下文:

上篇中我们介绍到:

1 $element.mousewheel(function(dir){
2      console.log(dir) ;
3 })
View Code

得到的结果为:鼠标滚轮 向上滚动 dir-->1, 向下滚动 dir-->-1

ok,有了这个结果 我们就可以做下边的工作了...

 to know what's I want...

  目标: 滚动鼠标滚轮实现图片合理的放大缩小,何为合理?即:不能让图片失真,至少比例要一致(成比例放大或缩小)

  思路:有了dir这个属性,让图片向上滚动时,成比例放大;向下滚动时,图片成比例缩小;

     也就是说 dir=1时,图片的宽高在原有基础上,保持比例一致的增大,dir=-1时,图片的宽高在原有基础上,保持比例一致的缩小。

     (此时的你是不已经 有点灵感了呢 :),貌似 这次重点不在如何判断鼠标的滚动方向啦,而是,如何 *合理的 放大和缩小了啊...)

 

来吧,忍不住了 我要 coding....

1.HTML + CSS:先来写个页面

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title>SE - 点击图片放大 显示 </title>
 6     <style type="text/css">
 7         html,body,* { margin: 0; padding: 0; }
 8         ul { list-style: none;  }
 9         li { float: left; margin-left:10px; }
10         ul li a { display: block; }
11     </style>
12 </head>
13 <body>
14     <ul id="picList">
15         <li><a href="#"><img src="images/photo1.jpg"></a></li>
16         <li><a href="#"><img src="images/photo2.jpg"></a></li>
17         <li><a href="#"><img src="images/photo3.jpg"></a></li>
18         <li><a href="#"><img src="images/photo4.jpg"></a></li>
19     </ul>
20 </body>
21 </html>
View Code

效果:

 

2.实现点击图片,弹出模态框,含有要放大的图片 (本人用的jquery实现),代码如下

HTML部分: 新加一个代表模态框的 div

<div id="modal" class="modal"> <img src="" /> </div>

style部分: 对模态框进行设置,图片的上下居中,左右居中( *这段代码很重要  

 1         .modal {
 2             display: none;
 3             position: absolute;
 4             top: 0;
 5             left: 0;
 6             z-index: 999;
 7             width: 100%;
 8             height: 100%;
 9             background-color: #000000;
10             -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=90);
11             filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=90);
12             background-color: rgba(0,0,0,0.8);
13             text-align: center;
14         }
15         .modal:before {
16             content: '';
17             display: inline-block;
18             height: 100%;
19             vertical-align: middle;
20             margin-right: -0.25em; /* Adjusts for spacing */
21         }
22         .modal img {
23             display: inline-block;
24             vertical-align: middle;
25             border: 6px solid white;
26             border-radius: 5px;
27         }
View Code

script部分:引入jquery, 实现弹出模态框,并且点击模态框,模态框消失

 1     <script type="text/javascript" src="../js/jquery-1.10.2.min.js"></script>
 2     <script type="text/javascript">
 3         $(function(){
 4             var smImgA = $('#picList li a'),            //small image
 5                 md = $('.modal');                       //遮罩层
 6                        
 7             //small images been clicked
 8             smImgA.on('click',function(e){
 9                 e.preventDefault();
10                 e.stopPropagation();
11                 //load the big image
12                 md.empty();
13                 $('<img src="" />').appendTo(md);
14                 var bgImg = $('.modal img');                //遮罩层内的 image
15                 var bgImgSrc = '';                          //big image src 
16                 bgImgSrc = $(this).find('img').attr('src').split('.')[0] + 'big.jpg';   //get the src
17                 bgImg.attr('src',bgImgSrc);
18                 //show the model
19                 md.show(200, bgImgShow);
20                 //method show() callback function
21                 function bgImgShow(e){
22                     //do something。。。。。。
23                     alert("显示模态框后,都something。。。");
24                 };
25             });
26  
27             //.modal been click
28             md.on('click',function(e){  //点击模态框,它隐藏
29                 $(this).hide(300);
30             }); 
31         });
32     </script>
View Code

效果:

 

 3.重点来了,目的:当鼠标在模态框中的图片上 滚动滚轮的时候,图片合理放大 我的理解:成比例放大,不能溢出屏幕 

 script部分:上一节自制的鼠标滚动事件,得到应用啦

  第1步:引入扩展

 1         $.fn.extend({
 2             mousewheel: function( fn ){
 3                 //judge the brower's mousewheel event, bind the event to element 
 4                 var toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
 5                         ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
 6                 var el = this[0];           //this[0];  jquery对象 转 JS对象(因addEventListener是JS对象的监听事件)
 7                 if( el.addEventListener ){  
 8                    for( var i = toBind.length; i; ){
 9                        el.addEventListener(toBind[--i],handleFun,false);
10                    }
11                 }
12                 else {
13                     el.onmousewheel = handleFun;
14                 }
15 
16                 //deal with the mousewheel
17                 function handleFun(e){
18                    var driect = 0, delta=0; //driect:滚动方向  delta:各浏览器监听滚动事件的属性值
19                    var e = e || window.event;
20                    if ( e.wheelDelta ){ delta = e.wheelDelta }
21                    else if ( e.deltaY   ){ delta = e.deltaY * -1 }
22                    else if( e.wheelDeltaY ) { delta = e.wheelDeltaY }
23                    else { 
24                         console.log('get delta,have somethings wrong...');
25                    }
26                    delta==0 ? console.log('get delta,have somethings wrong...') :
27                    delta>0  ? driect=1 : driect=-1; 
28 
29                    typeof fn==='function' ? fn( $(el) ,driect ) : '';
30                 }
31             }
32 
33         });
View Code

  第2步:实现图片 放大 和 缩小;因为图片的缩放只有在模态框显示后才可以发生,所以我把这一步骤放到了 show()事件的回调函数里,也以便获得图片的真实宽高。我的想法:图片newWidth = realWidth + realWidth*(1+dir*0.1), 也许你已经看出来了,这就是 因为dir=(+1或-1),所以,图片的新宽度 = 真实宽度 + (放大或缩小的宽度),对就这么简单的思路,ok,开干

 1                 //method show() callback function
 2                function bgImgShow(e){
 3                     var realWidth = bgImg.width(),  realHeight = bgImg.height();//图片真实宽高
 4                     //mousewheel diy
 5                     var imgSize=1;
 6                     bgImg.mousewheel(function( $this,dir ){
 7                         imgSize = imgSize + dir*0.1;
 8                         var newW = realWidth * imgSize, newH = realHeight * imgSize;
 9                         $this.width( newW );
10                         $this.height( newH );
11                     });                 
12                 };
View Code

ok,已实现 图片的放大缩小的功能,但是此时的功能是有瑕疵的,就是图片可以无限放大和缩小,做原理讲述还是可以的,但是,这并不符合场景的应用,所以有了第3步的合理化。

  第3步:实现图片放大和缩小的和合理化(即,对图片的可 成比例放大和缩小 的范围做限制)。

look at my code.....

 

 1                function bgImgShow(e){
 2                     var winW = $(window).width(),   winH = $(window).height();  //window的宽高
 3                     var limW = 0.9 * winW,          limH = 0.9 * winH;          //可允许图片显示最大宽高
 4                     var realWidth = bgImg.width(),  realHeight = bgImg.height();//图片真实宽高
 5                     var rdW = limW / realWidth,     rdH = limH / realHeight;    //得到图片宽高与limit宽高比   
 6                     //mousewheel diy
 7                     var imgSize=1, minSize=0.2, maxSize= rdW>rdH ? rdH : rdW;
 8                     bgImg.mousewheel(function( $this,dir ){
 9                         console.log( dir );
10                         imgSize = imgSize + dir*0.1;
11                         imgSize<minSize ? imgSize=minSize : '';
12                         imgSize>maxSize ? imgSize=maxSize : '';
13                         var newW = realWidth * imgSize, newH = realHeight * imgSize;
14                         $this.width( newW );
15                         $this.height( newH );
16                     });                 
17                 };
View Code

测试:

结果:图片可以合理的放大和缩小,达成目标。

 

大功告成!! 此时呢,如果你已看过上一篇的 《自定义鼠标滚动事件》,再加上 这篇的 一个图片放大缩小的Demo,再加上一点点你的创造力,应该可以做出一个不错的关于鼠标滚动的应用啦。哈吼....

 

上完整代码,结束本文,有问题的话,欢迎大家留言讨论

  1 <!DOCTYPE html>
  2 <html>
  3 <head lang="en">
  4     <meta charset="UTF-8">
  5     <title>SE - 点击图片放大 显示 </title>
  6     <style type="text/css">
  7         html,body,* { margin: 0; padding: 0; }
  8         ul { list-style: none;  }
  9         li { float: left; margin-left:10px; }
 10         ul li a { display: block; }
 11 
 12         .modal {
 13             display: none;
 14             position: absolute;
 15             top: 0;
 16             left: 0;
 17             z-index: 999;
 18             width: 100%;
 19             height: 100%;
 20             background-color: #000000;
 21             -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=90);
 22             filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=90);
 23             background-color: rgba(0,0,0,0.8);
 24             text-align: center;
 25         }
 26         .modal:before {
 27             content: '';
 28             display: inline-block;
 29             height: 100%;
 30             vertical-align: middle;
 31             margin-right: -0.25em; /* Adjusts for spacing */
 32         }
 33         .modal img {
 34             display: inline-block;
 35             vertical-align: middle;
 36             border: 6px solid white;
 37             border-radius: 5px;
 38         }
 39 
 40     </style>
 41     <script type="text/javascript" src="../js/jquery-1.10.2.min.js"></script>
 42     <script type="text/javascript">
 43         $.fn.extend({
 44             mousewheel: function( fn ){
 45                 //judge the brower's mousewheel event, bind the event to element 
 46                 var toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
 47                         ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'];
 48                 var el = this[0];           //this[0];  jquery对象 转 JS对象(因addEventListener是JS对象的监听事件)
 49                 if( el.addEventListener ){  
 50                    for( var i = toBind.length; i; ){
 51                        el.addEventListener(toBind[--i],handleFun,false);
 52                    }
 53                 }
 54                 else {
 55                     el.onmousewheel = handleFun;
 56                 }
 57 
 58                 //deal with the mousewheel
 59                 function handleFun(e){
 60                    var driect = 0, delta=0; //driect:滚动方向  delta:各浏览器监听滚动事件的属性值
 61                    var e = e || window.event;
 62                    if ( e.wheelDelta ){ delta = e.wheelDelta }
 63                    else if ( e.deltaY   ){ delta = e.deltaY * -1 }
 64                    else if( e.wheelDeltaY ) { delta = e.wheelDeltaY }
 65                    else { 
 66                         console.log('get delta,have somethings wrong...');
 67                    }
 68                    delta==0 ? console.log('get delta,have somethings wrong...') :
 69                    delta>0  ? driect=1 : driect=-1; 
 70 
 71                    typeof fn==='function' ? fn( $(el) ,driect ) : '';
 72                 }
 73             }
 74 
 75         });
 76 
 77         $(function(){
 78             var smImgA = $('#picList li a'),            //small image
 79                 md = $('.modal');                       //遮罩层
 80                        
 81             //small images been clicked
 82             smImgA.on('click',function(e){
 83                 e.preventDefault();
 84                 e.stopPropagation();
 85                 //load the big image
 86                 md.empty();
 87                 $('<img src="" />').appendTo(md);
 88                 var bgImg = $('.modal img');                //遮罩层内的 image
 89                 var bgImgSrc = '';                          //big image src 
 90                 bgImgSrc = $(this).find('img').attr('src').split('.')[0] + 'big.jpg';   //get the src
 91                 bgImg.attr('src',bgImgSrc);
 92                 //show the model
 93                 md.show(200, bgImgShow);
 94                 //method show() callback function
 95                function bgImgShow(e){
 96                     var winW = $(window).width(),   winH = $(window).height();  //window的宽高
 97                     var limW = 0.9 * winW,          limH = 0.9 * winH;          //可允许图片显示最大宽高
 98                     var realWidth = bgImg.width(),  realHeight = bgImg.height();//图片真实宽高
 99                     var rdW = limW / realWidth,     rdH = limH / realHeight;    //得到图片宽高与limit宽高比   
100                     //mousewheel diy
101                     var imgSize=1, minSize=0.2, maxSize= rdW>rdH ? rdH : rdW;
102                     bgImg.mousewheel(function( $this,dir ){
103                         console.log( dir );
104                         imgSize = imgSize + dir*0.1;
105                         imgSize<minSize ? imgSize=minSize : '';
106                         imgSize>maxSize ? imgSize=maxSize : '';
107                         var newW = realWidth * imgSize, newH = realHeight * imgSize;
108                         $this.width( newW );
109                         $this.height( newH );
110                     });                 
111                 };
112             });
113  
114             //.modal been click
115             md.on('click',function(e){  
116                 $(this).hide(300);
117             }); 
118         });
119     </script>
120 
121 
122 </head>
123 <body>
124     <ul id="picList">
125         <li><a href="#"><img src="images/photo1.jpg"></a></li>
126         <li><a href="#"><img src="images/photo2.jpg"></a></li>
127         <li><a href="#"><img src="images/photo3.jpg"></a></li>
128         <li><a href="#"><img src="images/photo4.jpg"></a></li>
129     </ul>
130 
131     <div id="modal" class="modal"> <img src="" /> </div>
132 </body>
133 </html>
View Code

 

  

勤能补拙是良训,一分辛苦一分甜。

 

posted @ 2016-11-07 17:20  驸马爷  阅读(3060)  评论(0编辑  收藏  举报