【发布时间】:2016-06-10 23:53:56
【问题描述】:
当用户在音乐图标播放和暂停之间切换时,我正在尝试更改网页上的“body”背景图像文件。
“body”元素的 CSS 如下所示:
body {
background: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/intro-bg.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}
所以在音乐功能中,我有两种状态,播放和暂停。我试图在每个“if”条件下更改图像,如下所示:
$("#music").click(function() {
if (playing) {
// Stop playing
document.body.style.background = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/intro-bg.jpg') no-repeat center center fixed";
$("body").css({backgroundSize: "cover"});
audioElement.pause();
} else {
// Start playing
if (!initDone) {
initDone = true;
document.body.style.background = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/header-background.jpg') no-repeat center center fixed";
audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/om_cut.mp3');
audioElement.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
}
audioElement.play();
}
$(this).find('i').toggleClass('fa-music fa-stop');
playing = !playing;
});
现在发生的情况是,当我播放音乐时,图像会发生变化,然后当我单击停止图标时,图像又会变回我的常规图像。但是下次我再次单击播放时,图像不会改变。所以这意味着我所做的只会被执行一次。每次在播放和暂停之间切换时,我怎样才能让它发生?
【问题讨论】:
-
没有一个真实的例子,调试起来很棘手......但我建议你将一个类切换到正文而不是设置那些内联样式。
-
@DaniP:就像我说的那样有效,但只执行一次。即使我切换播放和暂停图标,下一次图像仍然保持不变
标签: javascript jquery html css