如何获得img作为按钮?

时间:2019-01-05 19:52:51

标签: javascript html css

我的img作为按钮似乎存在问题。他们不会一起移动,而是分开移动。它不仅显示了img,还显示了按钮本身,我只想将img作为按钮。我试图将其设置为背景img,但没有任何效果。

我也希望按钮移至页面的背面并且不占用任何空间。当我使用z-index时:-1;按钮的功能消失,不再用作按钮。如何使用不同的代码执行此操作?

<!DOCTYPE html>
<html>


<div class="omheen">
<div>
<audio id="audioContainer">
 <source src="spraakbericht.m4a" type="audio/mpeg">
</audio>

<div id="memo">
 <button  id="play" onclick="playMp3()" type="button">
 <img class="memo" src="messages-05.png"/>
</div>
</button>
 <button id="pause" onclick="pauseMp3()" type="button">Pause Mp3</button> 

</div>
</div>

<script>
 const audioContainer = document.getElementById("audioContainer"); 

 function playMp3() { 
  audioContainer.play(); 
} 

function pauseMp3() { 
 audioContainer.pause(); 
} 


</script>

<script>
 var play = document.getElementById("play");
 var pause = document.getElementById("play");
 play.innerHTML = '<img src="\messages-05.png" />';
 pause.innerHTML = '<img src="\messages-05.png" />';
</script>   





</html>

非常感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

使用html5中的button元素,您可以将图像放在标签之间。还请确保使用按钮标签设置type属性,因为不同的浏览器对按钮元素使用不同的默认类型。为了使按钮不占用任何空间,您必须将显示设置为无或将其位置设置为绝对。由于元素的位置为静态,因此不会影响z-index级别。

答案 1 :(得分:0)

尝试在button标签内键入img标签。例如:

<button id="test><img src="/img/ex.png" alt="Test img"/></button>

答案 2 :(得分:0)

您可以使用

<input type="image" src="messages-05.png">

更多信息:https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/image

[更新] 您的代码看起来有些混乱。因此,我尝试对其进行一些清理,以显示我的建议的用途。

<!DOCTYPE html>
<html>
<head>
 <title>Title</title>
</head>
<body>
<div class="omheen">
 <div>
  <audio id="audioContainer">
   <source src="spraakbericht.m4a" type="audio/mpeg">
  </audio>
 </div>
 <div id="memo">
  <input type="image" id="playButton" src="messages-05.png" onclick="playMp3();">
  <input type="image" id="pauseButton" src="messages-05.png" onclick="pauseMp3();">
 </div>
</div>

<script>
 const audioContainer = document.getElementById("audioContainer");
 var playButton = document.getElementById("playButton");
 var pauseButton = document.getElementById("pauseButton"); 

 function playMp3() { 
  audioContainer.play(); 
 } 

 function pauseMp3() { 
  audioContainer.pause(); 
 } 
</script>
</body>
</html> 

在这些功能中,您可以通过更改playButton和pauseButton的src属性轻松更改按钮的图像。

请确保图像与html文件位于同一文件夹中。