JavaScript - 点击图片

标签 javascript image object click

我正在用 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);

关于JavaScript - 点击图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15671790/

相关文章:

javascript - Firefox 不应该执行 JavaScript

javascript - 如何根据输出值添加同一图像的 'x' 编号?

javascript - 从 json 响应中删除双引号

javascript - lodash 从中删除对象

Javascript 回调重置转换

javascript - 如何在不破坏 Angular 数据绑定(bind)的情况下更新集合中的项目?

php - Jquery从列表淡出后滑动到位置效果

html - 根据字体大小调整图像大小

css - 响应式设计 : fancybox thumbnail gallery , 调整大小并将图像垂直和水平放置在包装器的中心

object - 在Kotlin中无法在对象的父类(super class)构造函数中使用常量