javascript 制作可在点击时切换图像的 JS 按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9843543/
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 08:00:43  来源:igfitidea点击:

Making JS buttons that toggle their image on click

javascriptbuttontoggle

提问by Aurochs

I am doing something like this-

我正在做这样的事情-

http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_video_js_prop

http://www.w3schools.com/html5/tryit.asp?filename=tryhtml5_video_js_prop

but I want to replace the buttons with images that toggle to another image when clicked. In other words, the Play button will change to a Pause button.

但我想用单击时切换到另一个图像的图像替换按钮。换句话说,播放按钮将变为暂停按钮。

There are many tutorials that show how to do this with only one button but as soon as I add more buttons, the new ones don't work.

有很多教程展示了如何只用一个按钮来做到这一点,但是一旦我添加了更多按钮,新的按钮就不起作用了。

Any help appreciated!

任何帮助表示赞赏!

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>

<body>


<script type="text/javascript">

function changeIt()
{
var theImg = document.getElementsByTagName('img')[0].src;

var x = theImg.split("/");
var t = x.length-1;
var y = x[t];

if(y=='btnPlay.gif')
{
document.images.PlayOrPause.src='btnPause.gif'
}
if(y=='btnPause.gif')
{
document.images.PlayOrPause.src='btnPlay.gif'
}



}

</script>

<a href="#" onclick="changeIt()"><img src='btnPause.gif' name='PlayOrPause' border='0' /></a>

回答by The Alpha

Try this using input type image

使用输入类型图像试试这个

HTML

HTML

<input type="image" src="play.png" class="play" onclick="toggle(this);"/>

CSS

CSS

.play, .pause {width:100px;height:100px;}

?

?

JS

JS

function toggle(el){
    if(el.className!="pause")
    {
        el.src='pause.png';
        el.className="pause";
    }
    else if(el.className=="pause")
    {
        el.src='play.png';
        el.className="play";
    }

    return false;
}  ?

A fiddle is here. ?

一把小提琴在这里。?

回答by grep

swap : function(id) {
    var e = document.getElementById(id);
    e.className = (e.className == 'image1') 
        ? 'image2' 
        : 'image1';        
}

You can just make a function that checks the current class and switches it. This is the simplest example in which the 2 classes have different background images. The rest of the logic you could handle in a different function that manages the player's 'state' of playing, paused, etc.

您可以创建一个检查当前类并切换它的函数。这是最简单的示例,其中 2 个类具有不同的背景图像。您可以在管理播放器播放、暂停等“状态”的不同函数中处理其余逻辑。