简体   繁体   English

在悬停时播放音频文件

[英]Play an audio file on hover

I have made this script for my forum and I was wondering if anyone could guide me how to get the browser to play an audio file if the user hovers over the class style113 , but it has to give them a warning alert that says "audio is about to play" if they press ok on the alert it should play if they press cancel it should not. 我已经为我的论坛创建了这个脚本,我想知道是否有人可以指导我如何让浏览器播放音频文件,如果用户将鼠标悬停在类style113 ,但它必须给他们一个警告提示"audio is about to play"如果他们在警报上按下确定它应该播放,如果他们按下取消它不应该。 How can I achieve this? 我怎样才能做到这一点? Here is the script I have so far: 这是我到目前为止的脚本:

my script has been removed 

You can use the following code: 您可以使用以下代码:

var elems = document.getElementsByClassName("style113");
for(i in elems) {
    elems[i].addEventListener("mouseover", function() {
        if(confirm(" %%% CONFIRMATION MESSAGE %%% ")) {
            // %%% CODE TO PLAY SOUND %%%
        }
    });
}

What it does: 它能做什么:

  1. Loops over elements of class style113 循环类class style113元素
  2. Adds an event listener to each element to event mouseover 向事件mouseover每个元素添加事件侦听器
  3. In each event listener, creates a confirm() popup (has two buttons, one to confirm and one to cancel) 在每个事件监听器中,创建一个confirm()弹出窗口(有两个按钮,一个用于确认,一个用于取消)
  4. If the confirm() method returns true (if the positive button is clicked), then play sound 如果confirm()方法返回true (如果单击了正按钮),则播放声音

Working example on JSFiddle 关于JSFiddle的工作示例


UPDATE As per OP request in the comments below, you can add this code to your specific code in the for loop: 更新根据以下注释中的OP请求,您可以将此代码添加到for循环中的特定代码:

document.getElementsByClassName('style113')[x].addEventListener("mouseover", function() {
    if(confirm("audio is about to play")) {
        // %%% CODE TO PLAY SOUND %%%
    }
});

I'd also advise you to clean up your source code with better indenting practices. 我还建议您使用更好的缩进实践来清理源代码。 Also, avoid making too many DOM requests (eg, repetitive document.getElementsByClassName() ) and look instead to caching DOM requests . 此外,避免产生太多的DOM请求(例如,重复的document.getElementsByClassName() ),而是寻找缓存DOM请求

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM