QA@IT

色の設定が2回目から反映されて、初回が反映されない原因

7191 PV

下記のコードは、1分ごとに和暦と西暦に切り変わると『(カレンダー機能付き)デジタル時計』ですが、
問題があるのです。土曜日と日曜日にそれぞれ色を付けたのですが、2回目から反映されて初回は
反映されないのです。原因が分かりませんので、分かる方は教えていただけないでしょうか。

それと、文字数が増減することから後ろの要素から数えて設定したほうがやりやすいため、
CSSの"nth-last-child()"を使ったところ、前から数えて設定していました。
そこで、"nth-child()"で設定したところ、後から数えて設定するという逆転現象が生じました。
この原因も分かる方は教えていただけないでしょうか。

    <!DOCTYPE html>
    <html lang="ja">
    <head>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="Content-Script-Type" content="text/javascript">
    <meta http-equiv="Content-Style-Type" content="text/css">
    <title>文字マウスストーカー</title>


    <style type="text/css">

.sun:nth-child(14) {color:#ff0000;}
.sat:nth-child(14) {color:lightskyblue;}

    #myText {
    font-style: italic;
    font-weight: bold;
    font-family: 'comic sans ms', verdana, arial;
    color:gold;

    position: absolute;top: 0;left: 0;z-index: 3000;cursor: default;}
    #myText div {position: relative;}
    #myText div div {position: absolute;top: 0;left: 0;text-align: center;}

    </style>


    <script type="text/javascript">
    <!--

    ;(function(){

    var msg =  "";

    var size = 24;

    var circleY = 0.75; var circleX = 2;

    var letter_spacing = 5;

    var diameter = 10;

    var rotation = 0.4;
    var speed = 0.3;

    if (!window.addEventListener && !window.attachEvent || !document.createElement) return;

    msg = msg.split('');
    var n = msg.length - 1, a = Math.round(size * diameter * 0.208333), currStep = 20,
    ymouse = a * circleY + 20, xmouse = a * circleX + 20, y = [], x = [], Y = [], X = [],
    o = document.createElement('div'), oi = document.createElement('div'),
    b = document.compatMode && document.compatMode != "BackCompat"? document.documentElement : document.body,

    mouse = function(e){
     e = e || window.event;
     ymouse = !isNaN(e.pageY)? e.pageY : e.clientY; // y-position
     xmouse = !isNaN(e.pageX)? e.pageX : e.clientX; // x-position
    },

    makecircle = function(){ // rotation/positioning

     if(init.nopy){
      o.style.top = (b || document.body).scrollTop + 'px';
      o.style.left = (b || document.body).scrollLeft + 'px';
     };
     currStep -= rotation;
     for (var d, i = n; i > -1; --i){ // makes the circle
      d = document.getElementById('iemsg' + i).style;
      d.top = Math.round(y[i] + a * Math.sin((currStep + i) / letter_spacing) * circleY - 15) + 'px';
      d.left = Math.round(x[i] + a * Math.cos((currStep + i) / letter_spacing) * circleX) + 'px';
     };
    }

    var tMsg = ' ';
    var lastTLocale = '';

    function changeLang(Hour,Min,Sec){

  var t = tMsg;

  var t1=Hour + ":" + Min + ":" + Sec ;

      var date = new Date();
      var mt = date.getMinutes();

       if( mt%2==0 ){

          if(lastTLocale!= 'ja'){

              var time = new Date(),

                  m = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                  w = ["㊐", "㊊", "㊋", "㊌", "㊍", "㊎", "㊏"],

                 month = m[time.getMonth()],
                 day = time.getDate(),
                 week = w[time.getDay()];

  for (var d, i = n; i > -1; --i)
   {
    var elm = document.getElementById('iemsg' + i);
    elm.innerHTML = msg[i];
    elm.className = "";
    elm.style.color="";
      if(week==w[0]){
         elm.className = "sun";
                    }
      else if(week==w[6]){
         elm.className = "sat";
                    }
               }

               tA =  "◆" + " " +  time.toLocaleDateString("ja-JP-u-ca-japanese", { era: "long", year: "numeric" }).replace(/\u200e/g, "").replace(" ", "").replace(/(^|[^\d])1(?=$|[^\d])/, '$1元') + " " + month + day + "日" + " " + week + " " + "★" + "★" + " " + "◆";
              lastTLocale = 'ja';
        }
               t = tA + " " + t1;
}
    else{

          if(lastTLocale != 'en'){

             var time = new Date(),
                  w = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
                  m = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],

                 week = w[time.getDay()],
                 month = m[time.getMonth()],
                 day = time.getDate(),
                 year = time.getYear() + 1900;

                    if ((day == 1 ) || (day == 21 ) || (day == 31 )) {
                        day = day + "st";
                    }
                    else if ((day == 2 ) || (day == 22 )) {
                        day = day + "nd";
                    }
                    else if ((day == 3 ) || (day == 23 )) {
                        day = day + "rd";
                    }
                    else {
                        day = day + "th";
                    }

  for (var d, i = n; i > -1; --i)
   {
    var elm = document.getElementById('iemsg' + i);
    elm.innerHTML = msg[i];
    elm.style.color="";
    elm.className = "";
      if(week==w[0]){
        if((i>1)&&(i<5)){
          elm.style.color="red";
                    }
               }
      else if(week==w[6]){
        if((i>1)&&(i<5)){
          elm.style.color="lightskyblue";
                    }
               }
         }


                tB = "★" + " " + week + " " + day + " " + month + " " + year;
                lastTLocale = 'en';
       }
                t = tB + " " + t1;
    }
        var currentLength = msg.length;

      if (t != tMsg) {
        tMsg=t;

        // 状態の変更
        msg = t.split('');
        n = msg.length - 1;

        // 文字要素の変更
        for (var i = Math.max(currentLength, msg.length) - 1; i > -1; --i)
        {
            var d = i < currentLength ? document.getElementById('iemsg' + i) : null;
            if (d)
            {
                if (i < t.length)
                {
                    // 既存要素の内容変更
                    d.innerHTML = msg[i];
                }
                else
                {
                    // 不要になった要素の削除
                    d.parentElement.removeChild(d);
                }
            }
            else
            {
                // 不足要素の追加
                d = document.createElement('div');
                d.id = 'iemsg' + i;
                d.style.height = d.style.width = a + 'px';
                d.appendChild(document.createTextNode(msg[i]));
                oi.appendChild(d); y[i] = x[i] = Y[i] = X[i] = 0;
            }
        }
    };

    ascroll = function(){

     ymouse += window.pageYOffset;
     xmouse += window.pageXOffset;
     window.removeEventListener('scroll', ascroll, false);
    };

    o.id = 'myText'; o.style.fontSize = size + 'px';
    }

    function drag(){
     var time = new Date(),
         Hour = time.getHours(),
         Min = time.getMinutes(),
         Sec = time.getSeconds();

        if(Hour <= 9) { 
                       Hour = "0" + Hour; 
}
        if(Min <= 9) { 
                       Min = "0" + Min; 
}
        if(Sec <= 9) { 
                       Sec =  "0" +  Sec; 
}

     y[0] = Y[0] += (ymouse - Y[0]) * speed;
     x[0] = X[0] += (xmouse - 20 - X[0]) * speed;
     for (var i = n; i > 0; --i){
      y[i] = Y[i] += (y[i-1] - Y[i]) * speed;
      x[i] = X[i] += (x[i-1] - X[i]) * speed;
     };
     makecircle();changeLang(Hour,Min,Sec);
    }

    function init(){
     if(!isNaN(window.pageYOffset)){
      ymouse += window.pageYOffset;
      xmouse += window.pageXOffset;
     } else init.nopy = true;
     for (var d, i = n; i > -1; --i){
      d = document.createElement('div'); d.id = 'iemsg' + i;
      d.style.height = d.style.width = a + 'px';
      d.appendChild(document.createTextNode(msg[i]));
      oi.appendChild(d); y[i] = x[i] = Y[i] = X[i] = 0;
     };
     o.appendChild(oi); document.body.appendChild(o);
     setInterval(drag, 25);
    }

    if (window.addEventListener){

     window.addEventListener('load', init, false);
     document.addEventListener('mouseover', mouse, false);
     document.addEventListener('mousemove', mouse, false);
      if (/Apple/.test(navigator.vendor))
       window.addEventListener('scroll', ascroll, false);
    }
    else if (window.attachEvent){
     window.attachEvent('onload', init);
     document.attachEvent('onmousemove', mouse);
    }
    })();
    // -->
    </script>

    </head>

    <body bgcolor="black">

    </body>
    </html>

関連箇所は、changeLang()関数内の下記の部分です。

  for (var d, i = n; i > -1; --i)
   {
    var elm = document.getElementById('iemsg' + i);
    elm.innerHTML = msg[i];
    elm.style.color="";
      if(week==w[0]){
         elm.className = "sun";
                    }
      else if(week==w[6]){
         elm.className = "sat";
                    }
               }
~~~
  for (var d, i = n; i > -1; --i)
   {
    var elm = document.getElementById('iemsg' + i);
    elm.innerHTML = msg[i];
    elm.style.color="";
      if(week==w[0]){
        if((i>1)&&(i<5)){
          elm.style.color="red";
                    }
               }
      else if(week==w[6]){
        if((i>1)&&(i<5)){
          elm.style.color="lightskyblue";
                    }
               }
         }

回答

初期値の方に設定すれば初回も色は付きますが、文字が増減するので後ろから設定しても
ズレが生じるようです。順番を『デジタル時計,曜日,元号,月,日』とすると、
やりやすいのではないでしょうか。
また、曜日を最後に持って来て、下記のように書き換えると、うまく行きました。

CSS

.sun:nth-child(1) {color:#ff0000;}
.sat:nth-child(1) {color:lightskyblue;}
.others:nth-child(1) {color:silver;}

javascript

    ;(function(){

    var msg = "                                   "; //最大35字に設定。スペースで調節。

~~~


    var tMsg = ' ';
    var lastTLocale = '';

    function changeLang(Hour,Min,Sec){

  var t = tMsg;

  var t1 = Hour + ":" + Min + ":" + Sec + " ";

      var date = new Date();
      var mt = date.getMinutes();

       if( mt%2==0 ){
           var time = new Date(),
               w = ["㊐", "㊊", "㊋", "㊌", "㊍", "㊎", "㊏"],
               week = w[time.getDay()];
          if(lastTLocale!= 'ja'){
             var time = new Date(),
                 m = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                 month = m[time.getMonth()],
                 day = time.getDate();

  for (var d, i = n; i > -1; --i)
   {
    var elm = document.getElementById('iemsg' + i);
    elm.innerHTML = msg[i];
    elm.className = "";
    elm.style.color="";
      if(week==w[2]){
            elm.className = "sun";
                  }
      else if(week==w[6]){
            elm.className = "sat";
                  }
      else {
            elm.className ="others";
                  }
 }

               tA = "◆" + " " + time.toLocaleDateString("ja-JP-u-ca-japanese", { era: "long", year: "numeric" }).
              replace(/\u200e/g, "").replace(" ", "").replace(/(^|[^\d])1(?=$|[^\d])/, '$1元') + " " + month +
              day + "日" + " " + "★" + "★" + " " + "◆" + " ";
              lastTLocale = 'ja';
        }
               t = tA + t1 + week;
}
    else{

          if(lastTLocale != 'en'){

             var time = new Date(),
                  w = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
                  m = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],

                 week = w[time.getDay()],
                 month = m[time.getMonth()],
                 day = time.getDate(),
                 year = time.getYear() + 1900;

                    if ((day == 1 ) || (day == 21 ) || (day == 31 )) {
                        day = day + "st";
                    }
                    else if ((day == 2 ) || (day == 22 )) {
                        day = day + "nd";
                    }
                    else if ((day == 3 ) || (day == 23 )) {
                        day = day + "rd";
                    }
                    else {
                        day = day + "th";
                    }

  for (var d, i = n; i > -1; --i)
   {
    var elm = document.getElementById('iemsg' + i);
    elm.innerHTML = msg[i];
    elm.style.color="";
    elm.className = "";
      if(week==w[5]){
        if((i>1)&&(i<5)){
          elm.style.color="red";
                    }
               }
      else if(week==w[6]){
        if((i>1)&&(i<5)){
          elm.style.color="lightskyblue";
                    }
               }
      else {
        if((i>1)&&(i<5)){
          elm.style.color="silver";
                    }
               }
         }
                tB = "★" + " " + week + " " + day + " " + month + " " + year + " ";
                lastTLocale = 'en';
       }
                t = tB + t1;
    }
        var currentLength = msg.length;

~~~
編集 履歴 (1)
ウォッチ

この質問への回答やコメントをメールでお知らせします。