2016-12-23 5 views
0

にマウスのクリックやマウスダウンの違いをどのように処理するか、一度発生 - そのマウスクリックは一度だけ発生しますが、マウスがダウンして、すべてが私のマウスをダニ発生し、ここでダウンなぜOnMouseDownイベントのマウスホールドイベント

ですが、私の単純な例ではあります - 私はマウスクリックではなくマウスを使用している理由は分かりません。

<canvas id="drawhere" onmousedown="console.log('HH')" width="600" height="500"></canvas> 

「HH」は一度だけ書き込みます!マウスを上下に再び - 私は私のマウスがダウンしているとして、それはすべてのダニを書き込む必要が再び

それを書くために - 私はjqueryのを使用していない任意のヘルプ:))

、ジャバスクリプトのみ

document.getElementById("drawhere").addEventListener("mousemove", function(){ 
    console.log("mouse event!"); 
}); 

ワーキングペン:代わりに "onmouseover属性" "れるonmousemove"

+0

何をあなたを定義してください「ダニ」と呼んでいる。 –

+1

['mousedown'](https://developer.mozilla.org/en-US/docs/Web/Events/mousedown)は、ユーザーがボタンを押したときのみ起動します。それは連続的に発射されません。 –

答えて

1

mouseup and mousedownは、連続的に発火するとは考えられません。彼らは一回の行動が起こったことを伝えるためのものです。

ただし、カスタムタイマー(setInterval()より具体的には)mousedownでトリガとmouseupにキャンセルされると、この効果を実現できます。

document.getElementById("main"); 
 

 
// Variable to hold a reference to the timer 
 
var timer = null; 
 

 
// Set up an event handler for mousedown 
 
main.addEventListener("mousedown", function(evt){ 
 
    // Start a timer that fires a function at 50 millisecond intervals 
 
    timer = setInterval(function(){ 
 
    // the function can do whatever you need it to 
 
    console.log("Mous is down!"); 
 
    }, 50); 
 
}); 
 

 

 
// Set up a custom mouseup event handler 
 
main.addEventListener("mouseup", function(evt){ 
 
    // Cancel the previously initiated timer function 
 
    clearInterval(timer); 
 
    
 
    // And, do whatever else you need to: 
 
    console.log("Mouse is Up!"); 
 
}); 
 

 
// Set up a custom mouseleave event handler so that 
 
// if the mouse is dragged out of the original element 
 
// and then the mouse is released, the timer will stop 
 
main.addEventListener("mouseleave", function(evt){ 
 
    // Cancel the previously initiated timer function 
 
    clearInterval(timer); 
 
    
 
    // And, do whatever else you need to: 
 
    console.log("Mouse is no longer on element!"); 
 
});
#main { 
 
    background-color:yellow; 
 
    width: 300px; 
 
    height: 100px; 
 
}
<div id="main">Press and hold the mouse down inside me!</div>

+0

それは私の効果を達成するための最良の答えです - ありがとうございました –

+0

私はマウスを押してもボックス外にドラッグしたと思います>マウスをリリースしました。 マウスを上げてもmainでは起動せず、console.logは無限になります。私はマウスがアクティブなマウスダウンとフォーカスエリアについても確認しなければならないと思います。 – GeekAb

+0

本当ですが、それは質問で指定された要件ではありませんでした。私はそのシナリオに対応するための答えを更新しました。 –

0

使用して、私はあなたのjavascriptのコード内でこのような機能を使用することをお勧め http://codepen.io/parzibyte/full/ENzjvW/

+0

マウスボタンが連続して押されている間にマウスが動かず、あなたのコードペンがそれを示しているなら、 'mousemove'は動作しません。 –

+0

いいえ - 私たちはマウスクリックに関連する出来事について話します - 移動していないイベント以上 –

関連する問題