简体   繁体   中英

date conditionals in less css

I would like to use Less to create some CSS code valid only in a given time-interval.

I'd like to create a mixin like this

.showFromTo (@from, @to) when (`new Date().getTime() >= @from && new Date().getTime() <= @to`) {
    width: 100px; //for example
}

and then use it more or less like this:

.myClass { .showFromTo(`new Date(2014, 01, 02).getTime`, `new Date(2014, 01, 05).getTime()`) }

As it is it doesn't work... can anyone give me some help?

A Couple of Things

  1. Passing javascript date info, January is considered 0 and December 11 , so you need to account for that.
  2. As Stephen Thomas noted, I think he is correct, that javascript expressions in guards is not allowed, so the javascript evaluation must happen before the guard evaluation.

A Solution

The following accounts for both of these and seems to be functioning correctly:

LESS

.showFromTo (@startYear, @startMonth, @startDay, @endYear, @endMonth, @endDay) {
  @currentTime: `new Date().getTime()`;
  @start: `new Date(@{startYear}, @{startMonth} - 1, @{startDay}).getTime()`;
  @end: `new Date(@{endYear}, @{endMonth} - 1, @{endDay}).getTime()`;
  @displayCheck: `@{currentTime} >= @{start} && @{currentTime} <= @{end} ? true : false`;
  .display() when (@displayCheck = true) {
    width: 100px; //for example
  }
  .display();
}

.myClass {
  .showFromTo(2014, 1, 1, 2014, 12, 31); //displays if in 2014
}
.myClass2 {
  .showFromTo(2013, 1, 1, 2013, 12, 31); //does not display since we are past 2013
}

CSS Output (for the year 2014)

.myClass {
  width: 100px;
}

Thanks ScottS for the answer. I solved it this way:

@todayTs: `new Date().getTime()`;
.showFromTo (@fromTs, @toTs) when (@fromTs =< @todayTs) and (@todayTs =<  @toTs) {
    //style
}

called with

.myClass {
    .showFromTo(`new Date(2014, 00, 03).getTime()`, `new Date(2014, 00, 09).getTime()`);
}

In this way the comparison is easier but you need to pass the argument in a more complicated format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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