簡體   English   中英

JavaScript-單擊圖像

[英]JavaScript - Clicking on an image

我正在用JavaScript編程瀏覽器游戲,需要創建Card類。 此類具有(帶有其他變量)圖像,當我創建對象時應顯示該圖像。 單擊圖像時如何顯示對象的圖像並調用函數?

使用此代碼,我可以在任何位置顯示圖像,但是當我打開.htm文件而不是單擊圖像時,會立即調用OnClick函數。

<html>
<head> </head>
<body>
<script type="text/javascript">      
  function Card(photo){ // this is my object
      this.randomVariable=42;
      this.pic = new Image(); // creating an Image object inside my Card class.
        this.pic.src=photo;
        this.pic.height = 300;
        this.pic.width = 200;
        this.pic.style.position="absolute";  // this 3 lines should set the image's position, and it does.
        this.pic.style.top = 50 + "px"; 
        this.pic.style.left = 50 + "px";
        this.OnClick = document.write("lala");
  }

  var myObject = new Card("cardback.jpg");
  myObject = document.body.appendChild(coso1.pic); // is this how I should create the image? It appears where I want, but it doesn't seem a "clean" programming.
  myObject.OnClick = document.write("lala" + coso1.pic.offsetLeft + coso1.pic.offsetTop); // this is casted when I open the file, and not when I click on the image. *sadface*

</script>
</body>
</html>

請提供一些幫助,以幫助我檢測何時單擊圖像並以不太臟的方式顯示圖像(如果可能)?

提前致謝!

http://jsfiddle.net/CTWWk/1/

var image = new Image();
image.src = 'https://www.google.co.il/images/srpr/logo4w.png';

image.onclick = function(){
      alert('I Clicked an image now !');  
};

var divy = document.getElementById('divy');
divy.appendChild(image);

對您的代碼進行了一些更改。 希望能幫助到你!

<html>
<head> </head>
<body>
<script type="text/javascript">    
  function Card(photo){
     var cardInstance = new Image();
     cardInstance.src = photo;
     cardInstance.addEventListener('click', function (e) {
          alert(1);
      });
     return cardInstance;
  }  

  var myObject = new Card("cardback.jpg");
  document.body.appendChild(myObject);

</script>
</body>
</html>

暫無
暫無

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

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