簡體   English   中英

如何在javascript中傳遞鼠標單擊事件?

[英]How can I pass a mouse click event within javascript?

我正在嘗試為javascript實現拖放操作。我需要傳遞事件,但返回的是未定義的事件。 我已經嘗試過直接傳遞window.event。不起作用

var lens = svg.append("circle")
.attr("id","lens")
.attr("class","draggable")
.attr("cx",40)
.attr("cy",40)
.attr("r",40)
.style("fill","grey");

//Setting click handler
lens.on("click",function(e){
selectElement(e)});

 function selectElement(e) {       
     console.log(window.event); //This prints UNDEFINED
     console.log(e);  //This prints UNDEFINED

    var evt = e || window.event;    
     console.log(evt);  //This prints UNDEFINED
 }

SVG使用evt監視事件。 請嘗試以下操作:

 <!DOCTYPE HTML> <html> <head> <title>SVG evt</title> </head> <body> <svg width=400 height=400> <circle id=myCircle cx=200 cy=200 r=100 fill=blue stroke=none onClick=showEvt(evt) /> </svg> <script> function showEvt(evt) { var target=evt.target console.log(target.getAttribute("id")) } </script> </body> </html> 

您是否簽出了jQuery UI? https://jqueryui.com/這可能會對您有所幫助。 這是拖放的基本設置:

$( function() {
    $( "#draggable" ).draggable();
    $( "#droppable" ).droppable({
      drop: function( event, ui ) {
        $( this )
          .addClass( "ui-state-highlight" )
          .find( "p" )
            .html( "Dropped!" );
      }
    });
  } );
  </script>

關於您的點擊事件,請嘗試以下操作:

$('#id').click(function(){
  $(this).data('clicked', true);
});

這是指向Javascript Mouse Event教程的鏈接,該教程使您無需使用jQuery或其他庫即可綁定鼠標事件:

JavaScript鼠標事件

一個有用的小提琴例子:

https://jsfiddle.net/iamthejonsmith/q0sc4mae/

和示例代碼:

<input type="button" value="click me" id="btn">
<input type="button" value="right-click me" id="btn2">



document.getElementById('btn').onclick = function() {
  alert('click!')
}

document.getElementById('btn2').oncontextmenu = function() {
  alert('right click!')
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM