简体   繁体   English

如何在Javascript中单击鼠标来放置图像?

[英]How do I place an image with a mouse-click in Javascript?

To elaborate, if I click somewhere on the page, an image (that I add in the code) will be placed. 详细地说,如果我单击页面上的某处,将放置一张图像(我在代码中添加)。 I couldn't find any information on anything similar to this online. 我找不到任何与此在线类似的信息。 Help? 救命?

You need to use event listeners for the 'click' event. 您需要为“ click”事件使用事件监听器。 Create an image, set the relative url and append it to your document. 创建一个图像,设置相对URL并将其附加到您的文档中。

Something like this for example. 例如这样的事情。

document.getElementById('foo').addEventListener('click', function(e) {

    var img = document.createElement('img');

    img.setAttribute('src','http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png');

    e.target.appendChild(img);
});

Check the fiddle here . 这里检查小提琴。

This is just a basic example by the way. 顺便说一下,这只是一个基本示例。 You need to elaborate it to assure cross-browser compatibility, perhaps consider image preloading, etc. 您需要详细说明它,以确保跨浏览器的兼容性,或者考虑图像预加载等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM