javascript - 请使用相同的按钮播放和暂停音频
问题描述
我有这段代码,只是播放,但我想用同一个按钮(图像)播放和暂停,我不知道我需要添加什么,我需要做什么?请帮帮我
<script>
function play(){
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="image" id= "Portada1" src= "https://66.media.tumblr.com/dc48784826909289a58767fed35ba421/tumblr_pu7p4w8Jai1yrcbyio1_1280.jpg" alt ="Portada del sencillo Tim McGraw de Taylor Swift." onclick="audio.play ()">
<audio id="audio" src="Audio/Teardrops On My Guitar.mp3" ></audio>
</body>
解决方案
<input type='image'>
实际上是花哨的提交按钮,当嵌套在 a 中时可以实现全部功能<form>
,但出于 OP 的目的,<button>
带有 a 的 abackground-image
不仅在语义上是准确的,而且还确保不会有任何可能的副作用。
<button type='button'></button>
button { background: url(https://example.com/path/to/image.jpg)....}
要在音频对象上切换.play()
和.pause()
方法,请使用
if (audio.paused || audio.ended) {... //if audio is not playing
或者
if (audio.playing) {... // if audio is playing
document.querySelector('button').onclick = player;
function player(event) {
const clicked = event.target;
clicked.classList.toggle('playing');
const song = document.querySelector('audio');
if (song.paused || song.ended) {
song.play();
} else {
song.pause();
}
}
button {
background: url(https://www.hardwoodandhollywood.com/pop-culture-spin/wp-content/uploads/sites/7/2015/02/florencemachine.jpg)no-repeat;
background-size: contain;
display: inline-block;
width: 124px;
height: 86px;
cursor: pointer;
border: 3px solid rgba(158, 127, 103, 0.7);
box-shadow: 4px 6px 7px rgba(158, 127, 103, 0.6);
border-radius: 20%;
}
button:hover {
border: 3px solid rgba(158, 127, 103, 1);
}
.playing {
border: 3px solid rgba(58, 127, 203, 0.7);
box-shadow: 4px 6px 7px rgba(58, 127, 203, 0.6);
}
.playing:hover {
border: 3px solid rgba(58, 127, 203, 1);
}
button:focus {
outline: 0
}
<button type='button'></button>
<audio src='https://gldrv.s3.amazonaws.com/av/Florence_and_the_Machine-Dog_%20Days_are_Over.mp3'></audio>
推荐阅读
- html - 如果 div 存在,body 标签的意义何在
- rest - 尝试从 Powershell 调用 GitHub RestApi 调用以创建 Git 树并获取“解析 JSON 的问题”
- python - 在 Python 中的 subprocess.Popen 中指定标准输出中的文本类型
- sql - 查询调整/重写,需要关于使用 join 而不是 in 的建议以及在需要时进行更正的建议
- redux-form - Redux Form FieldArray 解析和格式化
- mongodb - 检查实体是否存在于 mongo 中,SpringData 在多文档事务中抛出异常计数是不允许的
- spring - 如何通过 Spring Webflux 中的 websockets 向特定客户端发送消息?
- typescript - typescript 编译器如何发现带有类型的 npm 包?
- ios - 如何使用 PacketLogger 分析蓝牙数据包?
- maven - Spring Boot 无法识别 mvn liquibase cli-changes,反之亦然