javascript 插入可点击的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8542083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:45:57  来源:igfitidea点击:

Inserting a clickable image

javascripthtmlcss

提问by Cecil Rodriguez

I want to insert a clickable image, that is, if any part of the image is clicked, it will either act like a button element, or more preferably, run a Javascript script.

我想插入一个可点击的图像,也就是说,如果图像的任何部分被点击,它要么像一个按钮元素,要么更优选地,运行一个 Javascript 脚本。

I was thinking of inserting an image into a button element, but as far as I can tell, that would NOT just make the whole image into a button, but rather insert it into a button box.

我正在考虑将图像插入按钮元素,但据我所知,这不仅会使整个图像变成按钮,而是将其插入按钮框。

How do I make a clickable image, that pulls up a script?

我如何制作一个可点击的图像,拉出一个脚本?

回答by Will

There are lots of ways to do this.

有很多方法可以做到这一点。

<img id="Img" src="img.jpg" />

Adding an onclick attribute:

添加一个 onclick 属性:

<img id="Img" src="img.jpg" onclick="myFunction()" />

Adding onclick event listener from script:

从脚本添加 onclick 事件侦听器:

document.getElementById( "Img" ).onclick = function() {
    // img clicked
};

Put image as button background

将图像作为按钮背景

<input type="button" style="background: url( img.jpg )" />