我正在尝试改变"身体"我的网页上的背景图像文件,当用户在音乐图标播放和暂停之间切换时。
以下是" 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;
});
现在发生的事情是,当我播放音乐时,图像会发生变化,然后当我点击停止图标时,图像会再次变回我的常规图像。但是下次我再次点击播放时图像不会改变。所以它意味着我只做了一次执行。每当我在播放和暂停之间切换时,我怎样才能让它发生?
答案 0 :(得分:1)
第一次,您正在设置此initDone = true;
因此,在第二次和后续调用中,if (!initDone)
条件会阻止图像更改。
将document.body.style.background =...
移到条件之上,它应该按照您的要求进行操作。
答案 1 :(得分:0)
在这种情况下if (!initDone) { .... }
你只需要制作改变背景的脚本。 https://jsfiddle.net/m2s5kho2/
var playing = false, initDone = false;
$("#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
document.body.style.background = "url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/665940/header-background.jpg') no-repeat center center fixed";
if (!initDone) {
initDone = true;
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;
});