简体   繁体   English

根据日期改变图像

[英]changing image depending on the day

I want to add a functionality to my site that changes the images shown depending on the day. 我想在我的网站上添加一项功能,根据当天更改显示的图像。 I haven't been able to quite wrap my head around it as I'm a bit of a novice. 因为我是一个新手,所以我无法完全绕过它。 My images are stored in images/week2/image_day_4. 我的图像存储在images / week2 / image_day_4中。 I am going to try to use a couple incrementing variables to access the image values, so if the day is day 4 in week 2 of membership the code should read something like 我将尝试使用几个递增变量来访问图像值,因此如果当天是第2周会员资格的第4天,代码应该读取类似的内容

"images/week_" + week + "/image_day_" + day;

every day since membership started, i'll increment day. 会员资格开始后每天都会增加。

Is there a better way to do this? 有一个更好的方法吗?

So if I understand that correctly, every day for some prolonged period of time of membership will display a different image. 因此,如果我理解正确,每天在一段时间内会员资格会显示出不同的形象。 Why do you need week then? 为什么你需要一周呢? One solution would be to just keep track of total days and create a basic JS object of key value pairs. 一种解决方案是仅跟踪总天数并创建关键值对的基本JS对象。 Keys could be the number of days, and value could be the url of the image. 键可以是天数,值可以是图像的URL。 For example: 例如:

JS Usage: JS用法:

var obj = {
    key1: value1,
    key2: value2
};

JS Example: JS示例:

var membershipImages = {
    1: "images/day1.jpg",
    2: "images/thatThing.png"
};

Then after you calculate a user's day of membership, all you would need to do is pull out the url: 然后在计算用户的会员日之后,您需要做的就是拉出网址:

someObject.setSomeProperty(membershipImages.getProperty("1"));

According to this documentation and this thread , you could use : 根据此文档和此主题 ,您可以使用:

function getWeekNumber(d) {
    // Copy date so don't modify original
    d = new Date(+d);
    d.setHours(0, 0, 0);
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setDate(d.getDate() + 4 - (d.getDay() || 7));
    // Get first day of year
    var yearStart = new Date(d.getFullYear(), 0, 1);
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7)
    // Return array of year and week number
    return weekNo;
}

var path = "images/week_" + getWeekNumber(new Date()) + "/image_day_" + new Date().getDay();
alert(path);

JSFiddle 的jsfiddle

EDIT : The new Date() statement can be easily converted to use the membership starting date. 编辑:可以轻松转换new Date()语句以使用成员资格开始日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM