我有一个触发按钮,可以打开一个模式,当有人单击它时,它会同时播放音频文件。到目前为止一切顺利。
我正在努力的地方是,如何仅在打开模态时播放音频文件?此刻它每次都播放声音,因此,如果有人打开它,或者有人关闭它。因此,每次点击触发器.pop-icon
。
JS:
$(document).ready(function () {
var e = document.createElement("audio");
(e.src = "https://intern.globallabs.de/message.mp3"),
(e.volume = 0.5),
(e.autoPlay = !1),
(e.preLoad = !0),
$(".pop-icon").click(function () {
e.play();
});
});
HTML触发器:
<div class="pop-icon">...</div>
答案 0 :(得分:1)
好的,我了解... 在这种情况下,您可以使用属性保存模式状态:
// Some shorthands
const $ = document;
$.get = $.getElementById;
const log = console.log;
const warn = console.warn;
const error = console.error;
const trigger = $.get('trigger');
trigger.addEventListener('click', function() {
if (trigger.getAttribute('data-is-open') == 'false') {
trigger.setAttribute('data-is-open', 'true');
$.get('modal').style.display = 'block';
trigger.innerHTML = 'close';
playSound('https://intern.globallabs.de/message.mp3');
} else {
$.get('modal').style.display = 'none';
trigger.innerHTML = 'reopen';
trigger.setAttribute('data-is-open', 'false');
}
});
function playSound(url) {
const audio = document.createElement('audio');
audio.src = url;
// Your audio settings
audio.play();
}
#modalContainer {
position: fixed;
bottom: 1rem;
right: 1rem;
}
#modal {
display: none;
width: 50px;
margin-bottom: 1rem;
padding: .5rem;
border: 1px solid;
border-radius: 4px;
z-index: 1000;
}
#trigger {
float: right;
}
<html>
<body>
<div id="modalContainer">
<div id="modal">
This is the Modal
</div>
<button id="trigger" data-is-open="false">open</button>
</div>
</body>
</html>
答案 1 :(得分:0)
你的意思是这样吗?
// Some shorthands
const $ = document;
$.get = $.getElementById;
const log = console.log;
const warn = console.warn;
const error = console.error;
$.body.addEventListener('click', function() {
$.get('trigger').addEventListener('click', function() {
$.get('overlay').style.display = 'block';
$.get('modal').style.display = 'block';
playSound('https://intern.globallabs.de/message.mp3');
});
});
function playSound(url) {
const audio = document.createElement('audio');
audio.src = url;
// Your audio settings
audio.play();
}
#overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
background-color: #0008;
z-index: 50;
}
#modal {
display: none;
width: 50%;
margin: 2rem auto;
padding: .5rem;
border: 1px solid;
border-radius: 4px;
z-index: 1000;
}
<html>
<body>
Click the button to <button id="trigger">open</button> the Modal and play the sound.
<div id="overlay"></div>
<div id="modal">
This is the Modal
</div>
</body>
</html>