当您点击播放按钮的图像时,我想要播放一个html音频元素。我在Angular 2工作,所以它比仅使用jQuery绑定要复杂一点......这就是我到目前为止所拥有的:
@Component({
selector: 'listen',
template: `
<h1>Play Your Greeting!</h1>
<img src="../images/play.svg" (click)="playMusic($event)">
<audio controls src="../music/06 What Is The Light_.mp3">
`,
styles: [`
img {
width: 30%;
}
`]
})
export class ListenComponent {
constructor(
private listenService: ListenService,
private route: ActivatedRoute,
private router: Router
) {}
playMusic(event) {
console.log(event.target);
event.target.play();
}
}
显然事件附加到图像上,但不知怎的,我需要在音频标签上调用.play()。
答案 0 :(得分:1)
您可以将局部变量分配给audio
元素,然后将其传递给方法调用
<img src="../images/play.svg" (click)="playMusic(audioEl)">
<audio #audioEl controls src="../music/06 What Is The Light_.mp3">
playMusic(el: HTMLAudioElement) {
el.play();
}
请参阅#audioEl
。这是将audio
元素分配给模板可访问变量。您可以看到它正在传递给playMusic
方法调用