0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jsで現在時刻と指定時刻を比較して、要素の表示非表示したい

Last updated at Posted at 2019-12-02

#新着情報とか、日付が来たら表示させたい

例えばこんな html

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>新着一覧</title>
</head>
<body>
    <ul>
        <li id="__target" data-showDate="2019/12/2" style="display:none;">項目1</li>
        <li>項目2</li>
        <li>項目3</li>
    </ul>
</body>
</html>

li[id="__target"] に data-showDate="この日付け以降は表示させる" と style="display:none;" の属性値を付加。

###こんなjs

//-----------------------------------
// 現在時刻をUNIXタイムで取得
//-----------------------------------
let _now  = new Date(),
    now_y = _now.getFullYear(),
    now_m = _now.getMonth() + 1,
    now_d = _now.getDate(),
    now_h = _now.getHours(),
    now_i = _now.getMinutes(),
    now_s = _now.getSeconds();
let now = now_y + '/' + now_m + '/' + now_d + ' ' + now_h + ':' + now_i + ':' + now_s;
// UNIXタイムスタンプで取得
let ux_now = Date.parse(now.replace( /-/g, '/')) / 1000;

//-----------------------------------
// 指定日付をUNIXタイムで取得
//-----------------------------------
let _showDate = document.getElementById('__target').getAttribute('data-showdate').split('/');
let showDate = _showDate[0] + '/' + _showDate[1] + '/' + _showDate[2] + ' 0:0:0';

// UNIXタイムスタンプで取得
let ux_showDate = Date.parse(showDate.replace( /-/g, '/')) / 1000;

// アクセス現在時刻が指定時刻を超えてたらSHOW
if ( ux_showDate < ux_now ) {
    document.getElementById('__target').style.display = '';
}  

応急処置的な時に使う。UNIXタイムスタンプ取得するとこ関数にしたほうが良いにきまってる。

当然 documentロード後じゃないとDOM取得できないので、__target読み込み後に実行。
data-showDate の日付を動かしてみて。

jsFiddle
https://jsfiddle.net/380mi/8rus3yv5/

Qiitaの使い方がこれでいいのかわからない

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?