我目前正在为一家营业时间如下的商店建立网站:
Tuesday & Wednesday: 10.00 - 17.00
Thursday: 10.00 - 12.30
其他日子(else)关闭。
我有一张打开图片 (images/open.png & images/open@2x.png
) 和一张关闭图片 (images/closed.png & images/closed @2x.png
).
我想在具有以下样式的类 (.open-closed) 中将这些图像显示为背景图像 (CSS):
.open-closed {
width: 48%;
background-color: #b3b3b3;
display: inline-block;
margin-top: 3%;
border: 5px solid white;
min-height: 300px;
float: left;
}
是的,它不是很正确,因为宽度以像素为单位更好,因为其中有图像,但我会在脚本完成后立即对其进行微调。
我对 jQuery/Javascript 了解不多,几乎一无所知。但我用谷歌搜索了一些片段并编辑了一些部分。我做错了什么?
<script language="JavaScript">
day=new Date() //..get the date
x=day.getHours() //..get the hour
if(x>=10 && x<17) {
document.write('<style type="text/css">.open-closed{background-image: url(images/open.png); background-repeat:no-repeat; width:300px; height: 285px; background-size: 300px 285px;}</style>')
} else
if (x>=17 && x<24) {
document.write('<style type="text/css">.open-closed{background: url(images/closed.png); background-repeat:no-repeat; width:300px; height: 285px; background-size: 300px 285px;}</style>')
} else
if (day=tuesday && x>=10 && x<12.30) {
document.write('<style type="text/css">.open-closed{background: url(images/open.png); background-repeat:no-repeat; width:300px; height: 285px; background-size: 300px 285px;}</style>')
} else
if (day=monday) {
document.write('<style type="text/css">.open-closed{background: url(images/closed.png); background-repeat:no-repeat; width:300px; height: 285px; background-size: 300px 285px;}</style>')
} else
if (day=friday) {
document.write('<style type="text/css">.open-closed{background: url(images/closed.png); background-repeat:no-repeat; width:300px; height: 285px; background-size: 300px 285px;}</style>')
} else
if (day=saturday) {
document.write('<style type="text/css">.open-closed{background: url(images/closed.png); background-repeat:no-repeat; width:300px; height: 285px; background-size: 300px 285px;}</style>')
} else
if (day=sunday) {
document.write('<style type="text/css">.open-closed{background: url(images/closed.png); background-repeat:no-repeat; width:300px; height: 285px; background-size: 300px 285px;}</style>')
}
</script>
这可能是一个非常愚蠢的错误......
最佳答案
我会说你比较错误的日子。
if(day.getDay() == 1) {
// Now it's monday
}
这就是我要说的方法。
此外:尽量避免添加新的 style
标签。定义 CSS 类并决定应用哪一个。假设您有两个类:.open 和 .closed。在这些类中,定义了每个背景图像。因此,您需要做的就是决定使用哪一个。
关于javascript - 根据时间更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13083865/