JavaScriptでマウスホイールイベントを扱い、スクロールも停止する方法
2006年08月17日-
スポンサード リンク
Mouse wheel programming in JavaScript
Web applications are becoming more and more like “normal” desktop applications. Of course, they are more and more functional, but smooth user interface acts the primary role. So we have drag and drop, autocompletition, and much more. Many of those nice features got possible only with help of AJAX.
JavaScriptでマウスホイールイベントの使い方が紹介されてます。
次のコードによってマウスホイールイベントを取得して、何らかの処理を行うことが出来ます。
※htmlとして保存してすぐサンプルとして使えます。handle関数を書き換えるだけで簡単にホイールの処理が実装できるはず。
<html>
<script language="javascript">function handle(delta) {
if (delta < 0)
// 下方向にまわした場合の処理
alert('down');
else
// 上方向にまわした場合の処理
alert('up');
}/** Event handler for mouse wheel event.
*/
function wheel(event){
var delta = 0;
if (!event) /* For IE. */
event = window.event;
if (event.wheelDelta) { /* IE/Opera. */
delta = event.wheelDelta/120;
if (window.opera)
delta = -delta;
} else if (event.detail) { /** Mozilla case. */
delta = -event.detail/3;
}
/** If delta is nonzero, handle it.
* Basically, delta is now positive if wheel was scrolled up,
* and negative, if wheel was scrolled down.
*/
if (delta)
handle(delta);
if (event.preventDefault) {
event.preventDefault();
}
event.returnValue = false;
}/** Initialization code.
* If you use your own event management code, change it as required.
*/
if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;</script>
<body>
<img src="" height="1000" width="1">
</body>
</html>
ホイールイベントを取得して何か処理させたあとは、スクロール処理を停止させたい場合も多いと思い、私の方で追記してみました。
オレンジ部分を追記することでスクロール処理を行わないようにすることが可能です。
スポンサード リンク
Advertisements
SITE PROFILE
最新のブログ記事(新着順)
- 2000種類以上の汎用ピクトグラムアイコン集「Atlas Icons」
- かわいい手書き風フォント「うさぎとまんげつのサンセリフ」
- ランディングページのサンプル集「Landings」
- WEBのUIコンポーネントギャラリー「The Component Gallery」
- 汎用で使える700+のピクトグラムアイコン「Sargam Icons」
- 白黒写真をWEB上で簡単にカラーにできる「Palette」
- iPhone14Proのモックアップ
- 建築素材風のおしゃれな背景画像「Architextures」
- クールな今どきのギャラリーサイトを作れるサンプル
- SVG形式の背景パターンなどをWEBで生成できる「fffuel」
- 過去のエントリ