我有这个代码改变图片取决于一天中的时间,星期几。我想做的是将这些图片作为背景。我该怎么做?
代码:
<script src="https://momentjs.com/downloads/moment.js">
</script>
<script src="https://momentjs.com/downloads/moment-timezone-with-
data.js">
</script>
<script type="text/javascript">
document.write("<p>");
var d = moment().tz('Europe/Oslo').format('dddd');
var hr = moment().tz('Europe/Oslo').format('k') ;
if (d=="Monday" && hr==0) {
documenet.write("<img src='https://static.wixstatic.com/media/e2aefa_7c93b6fa4d3549339bc3aac1311a4936~mv2.png/v1/crop/x_15,y_18,w_789,h_778/fill/w_270,h_270,al_c,usm_0.66_1.00_0.01/e2aefa_7c93b6fa4d3549339bc3aac1311a4936~mv2.png'>");
}
if (d=="Tuesday" && hr==22) {
document.write("<img src='https://static.wixstatic.com/media/e2aefa_7a8cd6f4b9904671a404f27a327db091~mv2.jpg/v1/crop/x_81,y_0,w_476,h_480/fill/w_270,h_272,al_c,q_80,usm_0.66_1.00_0.01/e2aefa_7a8cd6f4b9904671a404f27a327db091~mv2.jpg'>");
}
if (d=="Thursday" && hr==24) {
document.write("<img src='https://static.wixstatic.com/media/e2aefa_6ca6df712186436287875feeb5cb2232~mv2.jpg/v1/fill/w_269,h_269,al_c,q_80,usm_0.66_1.00_0.01/e2aefa_6ca6df712186436287875feeb5cb2232~mv2.jpg'>");
}
答案 0 :(得分:2)
<div id="my-element"></div>
在你的javascript中:
var myElement = document.getElementById('my-element');
myElement.style.backgroundImage = 'url("https://static.wixstatic.com/media/e2aefa_7c93b6fa4d3549339bc3aac1311a4936~mv2.png/v1/crop/x_15,y_18,w_789,h_778/fill/w_270,h_270,al_c,usm_0.66_1.00_0.01/e2aefa_7c93b6fa4d3549339bc3aac1311a4936~mv2.png")';
答案 1 :(得分:1)
例如,你需要一个div:
<div id="change">..<div>
然后使用document.getElementById('change')
查询此div并使用新网址更新其样式背景。
答案 2 :(得分:1)
可能的解决方案:
var d = moment().tz('Europe/Oslo').format('dddd');
var hr = moment().tz('Europe/Oslo').format('k') ;
var cssString;
if (hr>12 && d==="Sunday") {
// Sunday afternoon
cssString = "background-image:url(https://picsum.photos/1400/1000?image=11)";
}
else if(hr<11 && d==="Monday") {
// Monday morning
cssString = "background-image:url(https://picsum.photos/1400/1000?image=12)";
}
else {
cssString = "background-image:url(https://picsum.photos/1400/1000?image=13)";
}
document.body.insertAdjacentHTML("beforeend", `<div class="bg" style="${cssString}"></div>`);
的CSS:
.bg {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-size: cover;
}
工作示例: https://jsfiddle.net/v178Lo30/2/
您可以将我的解决方案与使用myElement.style.backgroundImage的pyramid ali提供的解决方案混合使用,这也是一种很好的方法。