单击按钮更改图像 [英] Change image in button on click

查看:101
本文介绍了单击按钮更改图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有图像的按钮,我想在点击时交换。我得到了那部分工作,但现在我还希望它再次点击时更改回原始图像。

I've got a button with an image inside that I want to swap when clicked. I got that part working, but now I also want it to change back to the original image when clicked again.

我正在使用的代码:

<button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>

和Javascript:

And the Javascript:

function action() {
  swapImage('images/image2.png');
};

var swapImage = function(src) {
  document.getElementById("ImageButton1").src = src;
}

提前致谢!

推荐答案

虽然可以使用全局变量,但您不需要。使用setAttribute / getAttribute时,添加在HTML中显示为attrib的内容。您还需要注意,添加全局只是将变量添加到窗口或导航器或文档对象(我不记得哪个)。

While you could use a global variable, you don't need to. When you use setAttribute/getAttribute, you add something that appears as an attrib in the HTML. You also need to be aware that adding a global simply adds the variable to the window or the navigator or the document object (I don't remember which).

你可以也将它添加到对象本身(即作为一个变量,如果查看html是不可见的,但如果你在调试器中查看html元素作为对象并查看它的属性,则可见。)

You can also add it to the object itself (i.e as a variable that isn't visible if the html is viewed, but is visible if you view the html element as an object in the debugger and look at it's properties.)

这是两种选择。 1以一种方式存储替代图像,使其在html中可见,另一种不存在。

Here's two alternatives. 1 stores the alternative image in a way that will cause it to visible in the html, the other doesn't.

<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}

window.addEventListener('load', mInit, false);

function mInit()
{
    var tgt = byId('ImageButton1');
    tgt.secondSource = 'images/image2.png';
}

function byId(e){return document.getElementById(e);}

function action() 
{
    var tgt = byId('ImageButton1');
    var tmp = tgt.src;
    tgt.src = tgt.secondSource;
    tgt.secondSource = tmp;
};

function action2()
{
    var tgt = byId('imgBtn1');
    var tmp = tgt.src;
    tgt.src = tgt.getAttribute('src2');
    tgt.setAttribute('src2', tmp);
}
</script>
<style>
</style>
</head>
<body>
    <button onClick="action();">click me<img src="images/image1.png" width="16px" id="ImageButton1"></button>
    <br>
    <button onClick="action2();">click me<img id='imgBtn1' src="images/image1.png" src2='images/image2.png' width="16px"></button>
    </body>
</html>

这篇关于单击按钮更改图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆