2011-09-14 337 views
4

如何用鼠標移動圖像? onmousedownonmousemove是處理權利的事件嗎?鼠標向下,鼠標移動和鼠標事件的圖像?

<html> 
    <body> 
    <script type="text/javascript"> 
    funcion good() 
    { 
    document.getElementById("omna"); 
    document.getElementById("omna).style.position="absolute"; 
    document.getElementById("omna").style.top=somevalue; 'these keeps changing 
    document.getElementById("omna").style.left=somevalue; ' these keeps changing 
    } 
    </script> 
    <img id="omna" src"/something.jpg" onmousedown="highlight() onmousemove="good()" onmousedown="stop()"> 'not working 
    </body> 
    </html> 

如何在圖像上使用mousedown事件?並與mousedown事件(我的意思是與圖片上的mousedown),它應該在JavaScript中不斷運行mousemove事件函數,並且當mouseup甚至發生它應該停止。 如何連續循環mousemove事件?無法解決問題。我在google上找到了一些解決方案,但無法弄清楚它的語法和全部。如果您以某種方式發佈相同的內容,請解釋我的解決方案。

很抱歉忘記告訴你我的mousedownmousevents不工作。有人建議使用錨標籤,那是好的?爲什麼mouseevents正在爲圖像工作?

回答

7

這樣的:

<html> 
    <head> 
    <style> 
     html,body { 
     height:100%; 
     } 
    </style> 


    <script type="text/javascript"> 
     var omnaEl,dragData=null; 
     function window_onload() { 
     omnaEl=document.getElementById("omna") 
     if(window.addEventListener) { 
      omnaEl.addEventListener('mousedown',startDrag,false); 
      document.body.addEventListener('mousemove',drag,false); 
      document.body.addEventListener('mouseup',stopDrag,false); 
     } 
     else if(window.attachEvent) { 
      omnaEl.attachEvent('onmousedown',startDrag); 
      document.body.attachEvent('onmousemove',drag); 
      document.body.attachEvent('onmouseup',stopDrag); 
     } 
     } 


     function startDrag(ev) { 
     if(!dragData) { 
      ev=ev||event; 
      dragData={ 
      x: ev.clientX-omnaEl.offsetLeft, 
      y: ev.clientY-omnaEl.offsetTop 
      }; 
     }; 
     } 
     function drag(ev) { 
     if(dragData) { 
      ev=ev||event; 
      omnaEl.style.left=ev.clientX-dragData.x+"px"; 
      omnaEl.style.top=ev.clientY-dragData.y+"px"; 
     } 
     } 
     function stopDrag(ev) { 
     if(dragData) { 
      ev=ev||event; 
      omnaEl.style.left=ev.clientX-dragData.x+"px"; 
      omnaEl.style.top=ev.clientY-dragData.y+"px"; 
      dragData=null; 
     } 
     } 

    </script> 
    </head> 
    <body onload='window_onload();'> 
    <img id="omna" src="http://t0.gstatic.com/images?q=tbn:ANd9GcRi-8XnnXwAZmz_5R5LHRHMNlnYYHCP4WqRdu6vhf_ru8wLK9XB3IrNrwix" 
     width="100px" height="100px" unselectable="on" style="position:absolute;user-select:none;-moz-user-select:none;-webkit-user-select:none;"/> 
    </body> 
</html> 
1

是的,這些都是正確的事件,但幾件事情要記住:

  1. 不要使用需要在標記中指定onmousemove風格事件綁定。閱讀本文以獲取有關javascript事件處理的更多背景信息。
  2. 與javascript結合使用,您很可能需要一些來自css的幫助。接受它 - 不要依靠javascript來完成所有繁重的工作。
  3. 如果您對JavaScript有經驗(知道語言的行爲),那麼我建議您使用jquery來完成繁重的工作(如事件綁定,屬性設置等) - 它將使您的代碼更加簡潔。

乾杯!