マウスホイールの横スクロール検出
タッチパッドとかマウスホイールとか、最近は360度全方向にスクロールできるようになってる。
これをjavascriptで検出して使おう。
実現方法
element.onmousewheel=function(e){ //use e.wheelDeltaX and e.wheelDeltaY }
これだけ。
別の手段-駄目な例
実は今までe.wheelDeltaしかなくて出来ないんだと思い込んでいて、次の方法で無理矢理実現してた。1. <div style="overflow:scroll">のスクロールバーを隠す
2. onscrollでスクロール検出(scrollLeft,scrollTop)
3. scrollLeft,scrollTopを元の位置に戻す
コードはこんな感じ
<script> function start(){ var scrollDiv=document.getElementById("scroll"); var box=document.getElementById("box"); var left=scrollDiv.scrollLeft=80; var top=scrollDiv.scrollTop=80; scrollDiv.onscroll=function(e){ e.deltaX=scrollDiv.scrollLeft-left; e.deltaY=scrollDiv.scrollTop-top; if(e.deltaX==0&&e.deltaY==0)return; scrollDiv.scrollLeft=left; scrollDiv.scrollTop=top; if(scrollDiv.onmousescroll)scrollDiv.onmousescroll(e); } var x=190,y=190,vx=0,vy=0; scrollDiv.onmousescroll=function(e){ vx=0.98*vx+e.deltaX*0.1; vy=0.98*vy+e.deltaY*0.1; } setInterval(function(){ vx*=0.98;vy*=0.98; x+=vx;y+=vy; if(x<0){x=0;vx*=-1;}if(x>380){x=380;vx*=-1;} if(y<0){y=0;vy*=-1;}if(y>380){y=380;vy*=-1;} box.style.left=x;box.style.top=y; },50); } </script> <body onload="start()"> <div style="border:1px solid red;position:relative;width:400px;height:400px;overflow:hidden;"> <div style="position:absolute;width:100%;height:100%;top:0;left:0" id="main"> <div style="position:absolute;width:20;height:20;background:blue;left:190;top:190" id="box"></div> </div> <div style="overflow:scroll;width:100%;height:100%;left:-40px;top:-40px;padding:40px;position:relative;" id="scroll"> <div style="width:100%;height:100%;padding:80px;position:absolute;left:0;top:0;"> </div> </div> </div>
サンプル http://www.geocities.jp/flyinpng/scroll20110527/index.html
もはや何の役にも立たないけど、wheelDeltaX/Yが使えないブラウザがあれば。