JavaScript - 单击图像

时间:2013-03-27 23:55:27

标签: javascript image object click

我正在用JavaScript编写一个浏览器游戏,需要创建一个Card Class。 此类具有(带有其他变量)图像,应在创建对象时显示该图像。如何在单击图像时显示对象的图像并调用函数?

使用此代码,我可以在任何地方显示图像,但是当我打开.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>

请帮助检测我何时点击图像并以较不脏的方式显示图像(如果可能的话)?

提前致谢!

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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>