javascript的日期對象+ setInterval() 和 clearInterval() + 設置一個簡單的電子時鐘

1、日期對象的實例化

var date=new Date();

2、getTime():返回1970年至今的毫秒數;

 

3、getFullYear():從Data對象以四位數字返回年份

 

4、getMonth():從Data對象返回月份(0—11)

 

5、getDate():從Data對象返回一個月中的某一天(1—31)

 

6、getHours():返回Data對象的小時(0~23)

 

7、getMinutes():返回Data對象的分鐘(0~59)

 

8、getSecond():返回Data對象的秒數(0~59)

 

9、getDay():從Data對象返回一週中的某一天(1~7)

 

 

例1: 獲取當前的日期

<script type="application/javascript">
      var date=new Date();
      var today=date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日";
      document.write(today);
  </script>

 

 

10、setInterval(): 方法可按照指定的週期(以毫秒計)來調用函數或計算表達式。這個方法會一直調用函數,直到clearInterval()被調用或窗口被關閉才停止調用函數。由setIntrval() 返回的 id 值可用作clearInterval() 方法的參數。

例:這是一個js實現css的動畫的過程,(在不使用css的animation 情況下

 <div id="fade-obj" style="width:300px;height:300px;background:#000"></div>
 <button id="fade-btn">淡出</button>
<script>
        var fade=document.querySelector("#fade-obj");//這是一個
        var fadeBtn=document.querySelector("#fade-btn");
        var id;
        var seed=100;
        fadeBtn.onclick=function () {
            if (this.innerHTML=="淡出"){
                this.innerHTML="淡入";
/*因爲fadeIn(),fadeOut無返回值,所以只需寫函數名,不需要括號。不然,setInterval()只會執行一次;*/
                id=setInterval(fadeIN,10)
            }else {
                this.innerHTML="淡出";
                id=setInterval(fadeOut,10);
            }
        }
        function fadeIN() {
            fadeBtn.disabled=true;
            seed--;
            console.log("fadeIN(): "+seed);
            fade.style.cssText="width:300px;height:300px;background:#000;opacity:"+seed/100+";";
            if (seed==0){
                window.clearInterval(id);//傳入setInterval的返回值
                fadeBtn.disabled=false;
            }
        }
        function fadeOut() {
            fadeBtn.disabled=true;
            seed++;
            console.log(seed);
            fade.style.cssText="width:300px;height:300px;background:#000;opacity:"+seed/100+";";
            if (seed==100){
                window.clearInterval(id);//傳入setInterval的返回值
                fadeBtn.disabled=false;
            }
</script>

 

12、例2:設置一個簡單的時鐘(年+月+日  星期  小時:分鐘:秒)

<p id="clock"></p>
  <script type="text/javascript">
    setInterval("setClock()",1000);//1秒更新一次
    function setClock() {
          var date=new Date();
          var today=date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日";
          var timeNow=date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
          document.getElementById("clock").innerText=today+"   "+"星期"
              +date.getDay()+"   "+timeNow;
      }
</script>

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章