我使用JavaScript编写浏览器游戏,需要创建一个卡片类。 这个类有(与其他变量)一个图像,当我创建一个对象时应该显示这个图像。如何在点击图像时显示对象的图像并调用函数?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>
请帮助我检测一下当我点击图像并以不太脏的方式显示图像(如果可能的话)?
在此先感谢!
为什么当我把你的代码放入html内容时图像不显示?
– CookieGuy 2013-03-28 00:34:24我只是增加了一些元素的id =“divy” - 看我发布的链接 - 这是完整的源代码[http://jsfiddle.net/CTWWk/1/](http:// jsfiddle.net/CTWWk/1/) – Adidi 2013-03-28 00:43:54
它不能在普通的JavaScript中运行?这段时间我可能会很烦,但重要的是我可以理解,以后再做更大的事情。提前致谢。 – CookieGuy 2013-03-28 14:34:43