2

JavaScript でブラウザ ゲームをプログラミングしており、カード クラスを作成する必要があります。このクラスには (他の変数と共に) 画像があり、オブジェクトを作成するときに表示する必要があります。オブジェクトの画像を表示し、画像がクリックされたときに関数を呼び出すにはどうすればよいですか?

このコードを使用すると、必要な場所に画像を表示できますが、画像をクリックしたときではなく、.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>

画像をクリックしたことを検出し、画像を汚れの少ない方法で表示する方法を教えてください (可能な場合)。

前もって感謝します!

4

2 に答える 2

0

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);
于 2013-03-28T00:05:08.010 に答える
0

コードにいくつかの変更を加えました。それが役に立てば幸い!

<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>
于 2013-03-28T00:16:29.310 に答える