整合營銷服務商

          電腦端+手機端+微信端=數據同步管理

          免費咨詢熱線:

          初學JS必會的10種JavaScript代碼優雅寫法

          初學JS必會的10種JavaScript代碼優雅寫法

          我們剛開始學習JS代碼時,我們只需要掌握JS中對應知識點就好,隨著對JS代碼的熟悉程度,我們就要思考如何寫出更優雅,更簡潔的代碼。

          接下來我分享10種常用JS代碼功能,通過常規寫法和優雅寫法的對比,來體現其優雅和簡潔性。代碼中用了ES6新特性,如果你對ES6不了解,可以先收藏好。在后期的VUE中,基本都在和ES6打交道。

          1、數組合并

          常規寫法

          利用concat方法來合并數組

          const apples=["紅蘋果", "綠蘋果"];
          const fruits=["西瓜", "草莓", "葡萄"].concat(apples);
          console.log(fruits); // ['西瓜', '草莓', '葡萄', '紅蘋果', '綠蘋果']

          優雅寫法

          利用ES6中的...擴展運算符來合并數組

          const apples=["紅蘋果", "綠蘋果"];
          const fruits=["西瓜", "草莓", "葡萄", ...apples];
          console.log(fruits);//['西瓜', '草莓', '葡萄', '紅蘋果', '綠蘋果']

          2、數組中取值

          常規寫法

          利用數組下標一個一個從數組中取數據

          const num=[1, 2];
          const num1=num[0];
          const num2=num[1];
          console.log(num1, num2); //1 2

          優雅寫法

          利用ES6的解構賦值來取值

          const num=[1, 2];
          const [num1, num2]=num;
          console.log(num1, num2);

          3、對象取值

          常規寫法

          對象.屬性名 的方式獲取屬性值

          const user={
             name: "張三",
             age: 30,
          };
          const name=user.name;
          const age=user.age;
          console.log(name, age);//"張三" 30

          優雅寫法

          利用ES6的解構賦值來實現

          const user={
             name: "張三",
             age: 30,
          };
          const { name, age }=user;
          console.log(name, age); // 張三 30

          4、數組循環

          常規寫法

          利用for循環來遍歷數組,從而取值

          const fruits=["西瓜", "草莓", "葡萄", "蘋果"];
          for (let i=0; i < fruits.length; i++) {
             console.log(fruits[i]);
          }

          優雅寫法

          利用ES6的for ... of來遍歷數組取值

          const fruits=["西瓜", "草莓", "葡萄", "蘋果"];
          for (fruit of fruits) {
             console.log(fruit);
          }

          5、回調函數

          常規寫法

          forEach中回調函數為普通函數

          const fruits=["西瓜", "草莓", "葡萄", "蘋果"];
          fruits.forEach(function (fruit) {
             console.log(fruit); //西瓜 草莓 葡萄 蘋果
          });

          優雅寫法

          forEach中回調函數為箭頭函數,如果箭頭函數中只有一句代碼,則可以省略{ }

          const fruits=["西瓜", "草莓", "葡萄", "蘋果"];
          fruits.forEach((fruit)=> console.log(fruit)); //西瓜 草莓 葡萄 蘋果

          6、數組搜索

          常規寫法

          數組中保存著每一條水果的信息,我們通過輸入水果名,到數組中查找到對應的信息。

          利用常規的for循環遍歷來查找。

          const fruits=[
            { name: "蘋果", order: 1 },
            { name: "李子", order: 4 },
            { name: "香蕉", order: 2 },
          ];
          function getApples(arr, value) {
             for (let index=0; index < arr.length; index++) {
                 if (arr[index].name===value) {
                     return arr[index];
                }
            }
          }
          const result=getApples(fruits, "蘋果");
          console.log(result); // { name: "蘋果", order: 1 }

          優雅寫法

          利用數組的find方法來實現搜索

          const fruits=[
            { name: "蘋果", order: 1 },
            { name: "李子", order: 4 },
            { name: "香蕉", order: 2 },
          ];
          function getApples(arr, value) {
             return arr.find((obj)=> obj.name===value);
          }
          const result=getApples(fruits, "李子");
          console.log(result);

          7、字符串轉換為數字

          常規寫法

          利用parseInt來實現

          const num=parseInt("10");
          console.log(num,typeof num); // 10   "number"

          優雅寫法

          利用+ 號來實現,不過只針對純數字的字符串有效

          const num=+"10";
          console.log(num,typeof num); //=> 10   "number"
          console.log(+"10"===10); // true;

          8、null值初始化

          常規寫法

          通過if判斷,如果為null,則初始化值為“普通用戶”

          //獲取用戶角色
          function getUserRole(role) {
             let userRole;
             if (role) {
                 userRole=role;
            } else {
                 userRole="普通用戶";
            }
             return userRole;
          }
          console.log(getUserRole()); //普通用戶
          console.log(getUserRole("管理員")); //管理員

          優雅寫法

          通過 || 或短路運算符來實現

          function getUserRole(role) {
             return role || "普通用戶"; // 默認值定義的常見方法
          }
          console.log(getUserRole()); // "普通用戶"
          console.log(getUserRole("管理員")); // "管理員";

          9、字符串拼接

          常規寫法

          const name="張三";
          const age=23;
          const message="大家好,我叫" + name + "今年" + age + "歲了!";
          console.log(message); //大家好,我叫張三,今年23歲了!

          優雅寫法

          const name="張三";
          const age=23;
          const message=`大家好,我叫${name},今年${age}歲了!`;
          console.log(message); // Hi DevPoint!

          10、對象合并

          常規寫法

          利用for循環來遍歷

          const employee={ name: "張三", age: 30 };
          const salary={ grade: "A" };
          const summary=salary; //用來做合并后對象
          for (const key in employee) {
             summary[key]=employee[key];
          }
          console.log(summary); // {grade: 'A', name: '張三', age: 30}

          優雅寫法

          利用es6的擴展運算符和解構賦值來實現

          const employee={ name: "張三", age: 30 };
          const salary={ grade: "A" };
          const summary={ ...employee, ...salary };
          console.log(summary); // { name: '張三', age: 30, grade: 'A' }
          

          最后我想告訴大家一個好消息,為了幫助關注我的同學,我們創建了《30天挑戰學習計劃》,全程免費,不涉及任何費用和利益,具體內容為以下4部分

          1、HTML5+CSS3核心知識

          2、30個HTML5+CSS3案例

          3、2個PC+移動+響應式綜合項目實戰

          4、網站全面上云部署與發布

          接下來我來詳細介紹下這個課程體系!


          為幫助到一部分同學不走彎路,真正達到一線互聯網大廠前端項目研發要求,首次實力寵粉,打造了《30天挑戰學習計劃》,內容如下:

          HTML/HTML5,CSS/CSS3,JavaScript,真實企業項目開發,云服務器部署上線,從入門到精通

          • PC端項目開發(1個)
          • 移動WebApp開發(2個)
          • 多端響應式開發(1個)

          共4大完整的項目開發 !一行一行代碼帶領實踐開發,實際企業開發怎么做我們就是怎么做。從學習一開始就進入工作狀態,省得浪費時間。

          從學習一開始就同步使用 Git 進行項目代碼的版本的管理,Markdown 記錄學習筆記,包括真實大廠項目的開發標準和設計規范,命名規范,項目代碼規范,SEO優化規范

          從藍湖UI設計稿 到 PC端,移動端,多端響應式開發項目開發

          • 真機調試,云服務部署上線;
          • Linux環境下 的 Nginx 部署,Nginx 性能優化;
          • Gzip 壓縮,HTTPS 加密協議,域名服務器備案,解析;
          • 企業項目域名跳轉的終極解決方案,多網站、多系統部署;
          • 使用 使用 Git 在線項目部署;

          這些內容在《30天挑戰學習計劃》中每一個細節都有講到,包含視頻+圖文教程+項目資料素材等。只為實力寵粉,真正一次掌握企業項目開發必備技能,不走彎路 !

          過程中【不涉及】任何費用和利益,非誠勿擾 。

          如果你沒有添加助理老師微信,可以添加下方微信,說明要參加30天挑戰學習計劃,來自頭條號!老師會邀請你進入學習,并給你發放相關資料

          30 天挑戰學習計劃 Web 前端從入門到實戰 | arry老師的博客-艾編程

          avaScript,也稱為JS,是一種遵循ECMAScript規范的編程語言。它是高級的、即時編譯的和多范式的。它有助于創建交互式網頁,并且是構建基于Web應用程序的重要元素。

          Javascript 庫是一組可以不時重復用于不同編程的代碼。換句話說,它大大節省了多次編寫代碼所需的時間。它降低了創建基于 JS 的應用程序的復雜性。它主要由許多元素組成,例如對象和函數。

          1.React

          React 是最著名和最常用的 Javascript 庫。它是一個由 Facebook 支持的開源庫它用于創建小型、中型和大型 Web 應用程序,以及創建高質量、功能豐富且直觀的網站。

          React 通常被稱為 SPA 或單頁應用程序,該術語用于能夠適應單個網頁的 Web 應用程序,而不需要不斷刷新頁面。通過使用 Javascript,我們可以在需要時加載內容。它使用有助于封裝代碼和狀態的組件,組件的使用有助于輕松控制復雜的用戶界面。

          React 使用 JSX,它是 HTML Javascript 的組合。它不是模板語言;它提供了 Javascript 的完整實踐經驗。有時很少有學習者會發現 JSX 相當復雜。但是,在使用它一段時間后,將了解它的好處。例如,JSX 可以輕松地將 JavaScript 表達式直接包裝在 HTML 中。從初學者的角度來看,React 的學習曲線很陡峭,

          2. jQuery

          jQuery 在開發領域已經存在很長時間,jQuery 是一個主要用于文檔對象模型 (DOM) 操作的庫。DOM 是一種樹狀結構,表示網頁上的所有元素。

          該庫可以選擇 DOM 元素、制作精美的設計/動畫、處理事件等等。jQuery 的主要目標是解決跨平臺不兼容問題并對其進行改進,同時促進 HTML Javascript 的分離。

          雖然很多瀏覽器都在使用 jQuery,但它已經不像幾年前那么重要了。現代瀏覽器已經在他們的 DOM 接口上工作和改進,使得對 jQuery 的需求比以前減少了。作為初學者,最好通過學習這一點來開始你的旅程。


          3. Vue

          Vue 基于 Virtual DOM 模型,具有基于組件的架構。可以使用 Vue 快速構建應用程序,并且它使用更少的代碼行來完成相同的任務,而對于其他一些庫來說,這需要更多的代碼。通過將 Vue 與其他工具和實用程序相結合,可以獲得一個成熟的框架作為一個框架,Vue 可以處理復雜的功能,例如路由、構建工具和狀態管理。

          4. D3.js

          D3 是一個 Javascript 庫,主要專注于數據可視化。D3 開發背后的主要原因是比其他庫更具視覺表現力,更先進,更符合最新趨勢這就是為什么 D3 被稱為最流行的 JavaScript 數據可視化庫之一。

          如果的意圖是制作精美的設計和實體,那么 D3 就是的理想之選。它可以是像餅圖和條形圖這樣簡單的東西,也可以是像 3D 圖這樣復雜的東西這個庫有一個強大的 API,類似于你在 jQuery 中找到的。簡而言之,如果正在尋找一個提供良好可視化效果的庫,那么 D3 將是的最佳選擇。

          JavaScript 在前端開發中處于首位HTML、CSS JavaScript 是前端開發的核心。Javascript 庫是主流,開發人員使用它們來創建更好的網站或應用程序。


          了解更多



          JavaScript是最好的語言之一,尤其是在前端開發中。在本文中,您將找到7個為初學者提供免費源代碼的最佳javascript項目。

          手把手教你7個有趣的JavaScript 項目-上「附源碼」(本篇)

          手把手教你7個有趣的JavaScript 項目-下「附源碼」


          1.使用JavaScript創建待辦事項列表應用



          如果您是javascript語言的初學者,則待辦事項列表應用程序是最好的和最容易的應用程序之一,如果您使用HTML CSS和一點點的javascript,則可以創建此簡單的待辦事項列表應用程序,您將找到源代碼這個js項目的底部。

          <!DOCTYPE html>
          <html lang="zh">
          <head>
          <meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <meta http-equiv="X-UA-Compatible" content="ie=edge" />
          <title>創建待辦事項列表應用</title>
          <style type="text/css">
          $primary: #313e50;
          $grey: #cdcdcd;
          $secondary: #1dd2af;
          
          %reset {
              margin: 0;
              padding: 0;
              border: none;
              outline: none;
              background: transparent;
          }
          
          %transition {
              transition: all 0.2s ease;
              -webkit-transition: all 0.2s ease;
          }
          
          body {
              background: #f1f1f1;
              margin-top: 2rem;
          }
          
          /*PEN STYLES*/
          .tasker {
              max-width: 400px;
              margin: 0 auto;
              .error {
                  display: none;
                  background: rgba(237, 28, 36, 0.7);
                  color: #fff;
                  padding: 14px;
                  margin-bottom: 10px;
                  border-radius: 5px;
                  text-align: center;
              }
          
              ul {
                  @extend %reset;
                  background: #fff;
              }
          
              li,
              .error,
              button,
              input {
                  @extend %reset;
                  font: 18px/1.25em Helvetica, Arial, Sans-serif;
              }
          }
          
          .tasker-header {
              display: inline-flex;
              background: $primary;
              justify-content: space-between;
              width: 100%;
              input,
              button {
                  color: #fff;
                  box-sizing: border-box;
                  font-size: 1.25em;
                  padding: 14px;
              }
          
              input {
                  flex-grow: 2;
              }
          
              button {
                  @extend %transition;
                  background: $secondary;
                  border-left: 1px solid ($secondary * 1.05);
                  &:hover {
                      background: $secondary * 1.1;
                  }
              }
          }
          
          .tasker-body {
              .task {
                  display: block;
                  position: relative;
                  padding: 14px 40px 14px 14px;
                  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
                  &:last-child {
                      border-bottom: none;
                  }
          
                  &:hover > button {
                      opacity: 1;
                  }
          
                  &.completed {
                      color: $grey;
                      text-decoration: line-through;
                  }
          
                  input {
                      margin-right: 10px;
                  }
          
                  button {
                      @extend %transition;
                      color: $grey;
                      margin: 14px;
                      position: absolute;
                      top: 0;
                      right: 0;
                      opacity: 0;
                      &:hover {
                          color: #ed1c24;
                      }
                  }
              }
          }
          </style>
          </head>
          <body>
          <!--PEN CODE-->
          <div id="tasker" class="tasker">
              <div id="error" class="error">Please enter a task</div>
              <div id="tasker-header" class="tasker-header">
                  <input type="text" id="input-task" placeholder="Enter a task">
                  <button id="add-task-btn"><i class="fa fa-fw fa-plus"></i>
                  </button>
              </div>
              <div class="tasker-body">
                  <ul id="tasks"></ul>
              </div>
          </div>
          <!--END PEN CODE-->
          <script type="text/javascript">
          (function() {
              'use strict';
              var tasker={
                  init: function() {
                      this.cacheDom();
                      this.bindEvents();
                      this.evalTasklist();
                  },
                  cacheDom: function() {
                      this.taskInput=document.getElementById("input-task");
                      this.addBtn=document.getElementById("add-task-btn");
                      this.tasklist=document.getElementById("tasks");
                      this.tasklistChildren=this.tasklist.children;
                      this.errorMessage=document.getElementById("error");
                  },
                  bindEvents: function() {
                      this.addBtn.onclick=this.addTask.bind(this);
                      this.taskInput.onkeypress=this.enterKey.bind(this);
                  },
                  evalTasklist: function() {
                      var i, chkBox, delBtn;
                      //BIND CLICK EVENTS TO ELEMENTS
                      for (i=0; i < this.tasklistChildren.length; i +=1) {
                          //ADD CLICK EVENT TO CHECKBOXES
                          chkBox=this.tasklistChildren[i].getElementsByTagName("input")[0];
                          chkBox.onclick=this.completeTask.bind(this, this.tasklistChildren[i], chkBox);
                          //ADD CLICK EVENT TO DELETE BUTTON
                          delBtn=this.tasklistChildren[i].getElementsByTagName("button")[0];
                          delBtn.onclick=this.delTask.bind(this, i);
                      }
                  },
                  render: function() {
                      var taskLi, taskChkbx, taskVal, taskBtn, taskTrsh;
                      //BUILD HTML
                      taskLi=document.createElement("li");
                      taskLi.setAttribute("class", "task");
                      //CHECKBOX
                      taskChkbx=document.createElement("input");
                      taskChkbx.setAttribute("type", "checkbox");
                      //USER TASK
                      taskVal=document.createTextNode(this.taskInput.value);
                      //DELETE BUTTON
                      taskBtn=document.createElement("button");
                      //TRASH ICON
                      taskTrsh=document.createElement("i");
                      taskTrsh.setAttribute("class", "fa fa-trash");
                      //INSTERT TRASH CAN INTO BUTTON
                      taskBtn.appendChild(taskTrsh);
          
                      //APPEND ELEMENTS TO TASKLI
                      taskLi.appendChild(taskChkbx);
                      taskLi.appendChild(taskVal);
                      taskLi.appendChild(taskBtn);
          
                      //ADD TASK TO TASK LIST
                      this.tasklist.appendChild(taskLi);
          
                  },
                  completeTask: function(i, chkBox) {
                      if (chkBox.checked) {
                          i.className="task completed";
                      } else {
                          this.incompleteTask(i);
                      }
                  },
                  incompleteTask: function(i) {
                      i.className="task";
                  },
                  enterKey: function(event) {
                      if (event.keyCode===13 || event.which===13) {
                          this.addTask();
                      }
                  },
                  addTask: function() {
                      var value=this.taskInput.value;
                      this.errorMessage.style.display="none";
          
                      if (value==="") {
                          this.error();
                      } else {
                          this.render();
                          this.taskInput.value="";
                          this.evalTasklist();
                      }
                  },
                  delTask: function(i) {
                      this.tasklist.children[i].remove();
                      this.evalTasklist();
                  },
                  error: function() {
                      this.errorMessage.style.display="block";
                  }
              };
          
              tasker.init();
          }());
          </script>
          </body>
          </html>

          2.使用JavaScript和CSS創建垂直時間軸(里程碑)



          您可以使用javascript初學者創建的第二個小項目是時間軸,許多現代網站都使用該時間軸使網站更具交互性和動態性。

          <!DOCTYPE html>
          <html lang="zh">
          <head>
          <meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <meta http-equiv="X-UA-Compatible" content="ie=edge" />
          <title>CSS創建垂直時間軸(里程碑)</title>
          <style type="text/css">
          *,
          *::before,
          *::after {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
          }
          
          body {
            font: normal 16px/1.5 "Helvetica Neue", sans-serif;
            background: #456990;
            color: #fff;
            overflow-x: hidden;
            padding-bottom: 50px;
          }  /* INTRO SECTION
          –––––––––––––––––––––––––––––––––––––––––––––––––– */
          
          .intro {
            background: #F45B69;
            padding: 100px 0;
          }
          
          .container {
            width: 90%;
            max-width: 1200px;
            margin: 0 auto;
            text-align: center;
          }
          
          h1 {
            font-size: 2.5rem;
          }
          
          
          /* TIMELINE
          –––––––––––––––––––––––––––––––––––––––––––––––––– */
          
          .timeline ul {
            background: #456990;
            padding: 50px 0;
          }
          
          .timeline ul li {
            list-style-type: none;
            position: relative;
            width: 6px;
            margin: 0 auto;
            padding-top: 50px;
            background: #fff;
          }
          
          .timeline ul li::after {
            content: '';
            position: absolute;
            left: 50%;
            bottom: 0;
            transform: translateX(-50%);
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: inherit;
          }
          
          .timeline ul li div {
            position: relative;
            bottom: 0;
            width: 400px;
            padding: 15px;
            background: #F45B69;
          }
          
          .timeline ul li div::before {
            content: '';
            position: absolute;
            bottom: 7px;
            width: 0;
            height: 0;
            border-style: solid;
          }
          
          .timeline ul li:nth-child(odd) div {
            left: 45px;
          }
          
          .timeline ul li:nth-child(odd) div::before {
            left: -15px;
            border-width: 8px 16px 8px 0;
            border-color: transparent #F45B69 transparent transparent;
          }
          
          .timeline ul li:nth-child(even) div {
            left: -439px;
          }
          
          .timeline ul li:nth-child(even) div::before {
            right: -15px;
            border-width: 8px 0 8px 16px;
            border-color: transparent transparent transparent #F45B69;
          }
          
          time {
            display: block;
            font-size: 1.2rem;
            font-weight: bold;
            margin-bottom: 8px;
          }
          
          
          /* EFFECTS
          –––––––––––––––––––––––––––––––––––––––––––––––––– */
          
          .timeline ul li::after {
            transition: background .5s ease-in-out;
          }
          
          .timeline ul li.in-view::after {
            background: #F45B69;
          }
          
          .timeline ul li div {
            visibility: hidden;
            opacity: 0;
            transition: all .5s ease-in-out;
          }
          
          .timeline ul li:nth-child(odd) div {
            transform: translate3d(200px, 0, 0);
          }
          
          .timeline ul li:nth-child(even) div {
            transform: translate3d(-200px, 0, 0);
          }
          
          .timeline ul li.in-view div {
            transform: none;
            visibility: visible;
            opacity: 1;
          }
          
          
          /* GENERAL MEDIA QUERIES
          –––––––––––––––––––––––––––––––––––––––––––––––––– */
          
          @media screen and (max-width: 900px) {
            .timeline ul li div {
              width: 250px;
            }
            .timeline ul li:nth-child(even) div {
              left: -289px;
              /*250+45-6*/
            }
          }
          
          @media screen and (max-width: 600px) {
            .timeline ul li {
              margin-left: 20px;
            }
            .timeline ul li div {
              width: calc(100vw - 91px);
            }
            .timeline ul li:nth-child(even) div {
              left: 45px;
            }
            .timeline ul li:nth-child(even) div::before {
              left: -15px;
              border-width: 8px 16px 8px 0;
              border-color: transparent #F45B69 transparent transparent;
            }
          }
          </style>
          </head>
          <body>
          <section class="intro">
            <div class="container">
              <h1>Vertical Timeline ↓</h1>
            </div>
          </section>
          
          <section class="timeline">
            <ul>
              <li>
                <div>
                  <time>1934</time> demo1
                </div>
              </li>
              <li>
                <div>
                  <time>1937</time> demo1
                </div>
              </li>
              <li>
                <div>
                  <time>1940</time> demo1
                </div>
              </li>
              <li>
                <div>
                  <time>1943</time> demo1
                </div>
              </li>
              <li>
                <div>
                  <time>1946</time> demo1
                </div>
              </li>
              <li>
                <div>
                  <time>1956</time> demo1
                </div>
              </li>
              <li>
                <div>
                  <time>1957</time> demo1
                </div>
              </li>
              <li>
                <div>
                  <time>1967</time>demo1
                </div>
              </li>
              <li>
                <div>
                  <time>1977</time> demo1
                </div>
              </li>
              <li>
                <div>
                  <time>1985</time> demo1
                </div>
              </li>
              <li>
                <div>
                  <time>2000</time> demo1
                </div>
              </li>
              <li>
                <div>
                  <time>2005</time> demo1
                </div>
              </li>
            </ul>
          </section>
          <script type="text/javascript">
          (function() {
          
            'use strict';
          
            // define variables
            var items=document.querySelectorAll(".timeline li");
          
            // check if an element is in viewport
            // http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport
            function isElementInViewport(el) {
              var rect=el.getBoundingClientRect();
              return (
                rect.top >=0 &&
                rect.left >=0 &&
                rect.bottom <=(window.innerHeight || document.documentElement.clientHeight) &&
                rect.right <=(window.innerWidth || document.documentElement.clientWidth)
              );
            }
          
            function callbackFunc() {
              for (var i=0; i < items.length; i++) {
                if (isElementInViewport(items[i])) {
                  items[i].classList.add("in-view");
                }
              }
            }
          
            // listen for events
            window.addEventListener("load", callbackFunc);
            window.addEventListener("resize", callbackFunc);
            window.addEventListener("scroll", callbackFunc);
          
          })();
          </script>
          </body>
          </html>

          3.用JavaScript構建一個簡單的井字游戲



          如果您想構建簡單而有趣的東西來練習JavaScript知識,那么使用HTML CSS和JS創建TIC TAC TOE游戲對您來說是個不錯的選擇,該游戲雖然簡單但并不容易,因此您需要專注于該項目的邏輯方面,因為它是該項目最具挑戰性的部分。

          <html>
              <head>
                <meta charset="utf-8" />
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="description" content="">
                <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                <title>FreeCodeCamp: Tictactoe</title>
          <style type="text/css">
          @import url(https://fonts.googleapis.com/css?family=Yesteryear);
          $app-background-color : #508ABB;
          $app-row-height : 100%;
          $winAnimStartColor : cyan;
          $winAnimEndColor : #508ABB;
          
          // html, body, div, span, a, li, td, th {
          //  font-family: 'Lato', sans-serif;
          //  font-weight: 300;
          //
          // }
          
          @-webkit-keyframes winAnim{
              0% {
              background-color: $winAnimStartColor;
            }
            100% {
              background-color: $winAnimEndColor;
            }
          }
          @-moz-keyframes winAnim{
            0% {
              background-color: $winAnimStartColor;
            }
            100% {
              background-color: $winAnimEndColor;
            }
          }
          @-o-keyframes winAnim {
            0% {
              background-color: $winAnimStartColor;
            }
            100% {
              background-color: $winAnimEndColor;
            }
          }
          @keyframes winAnim {
            0% {
              background-color: $winAnimStartColor;
            }
            100% {
              background-color: $winAnimEndColor;
            }
          }
          
          @keyframes winAnim {
            0% {
              background-color: $winAnimStartColor;
            }
            100% {
              background-color: $winAnimEndColor;
            }
          }
          
          *{
            -webkit-touch-callout: none;
            -webkit-user-select: none;
            -khtml-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            outline-style:none;/*IE*/
          }
          
          .center-box{
              margin : auto;
              position: absolute;
              top : 0;
              right : 0;
              bottom : 0;
              left : 0;
          }
          
          html,body{
              //background-image: linear-gradient(to bottom,#dddbd1,#d2dbdc);
              background-color: #d2dbdc;
              height : 100%;
              width  : 100%;
          }
          
          .app{
              @extend .center-box;
              width : 80%;
              height : 70%;
              max-width: 550px;
              background-color : $app-background-color;
              box-shadow: 0 5px 30px -5px rgba(0,0,0, .85);
              border-radius: 10px;
              .app-container,
              .app-row{
                  height: $app-row-height;
              }
          }
          .play-box,.symbol-option{
              font-family: 'Yesteryear', cursive;
          }
          
          .play-box{
              border-bottom : 2px solid #fff;
              border-right : 2px solid #fff;
              height : $app-row-height / 3;
              cursor: pointer;
              position: relative;
              &.last-right{
                  border-right : none;
              }
              &.last-bottom{
                  border-bottom : none;
              }
              &.win {
                  -webkit-animation: winAnim .2s ease-out infinite;
                -moz-animation:    winAnim .2s ease-out infinite;
                -o-animation:      winAnim .2s ease-out infinite;
                animation:         winAnim .2s ease-out infinite;
                  animation : winAnim .5s infinite;
              }
              .symbol{
                  @extend .center-box;
                  width: 50%;
                  height : 50px;
                  text-align: center;
                  line-height : 50px;
                  font-size: 35px;
                  color : white;
              }
          }
          
          .modal-content{
              .content{
                  padding : 15px;
                  text-align: center;
                  margin : 0;
                  &.body{
                      line-height: 2;
                  }
              }
              .symbol-options{
                  width: 200px;
                  margin-top: 10px;
                  .symbol-option{
                      &:first-child{
                          margin-right: 10px;
                      }
                      &:last-child{
                          margin-left: 10px;
                      }
                  }
              }
              .warning-hr{
                  margin: 0;
              }
          }
          </style>
              </head>
          
              <body>
                  <div class="app">
                      <div class="container-fluid app-container">
                      <div class="row app-row">
                          <div class="col-xs-4 play-box" id="0">
                              <div class="symbol"></div>
                          </div>
                          <div class="col-xs-4 play-box" id="1">
                              <div class="symbol"></div>
                          </div>
                          <div class="col-xs-4 play-box last-right" id="2">
                              <div class="symbol"></div>
                          </div>
                          <div class="col-xs-4 play-box" id="3">
                              <div class="symbol"></div>
                          </div>
                          <div class="col-xs-4 play-box" id="4">
                              <div class="symbol"></div>
                          </div>
                          <div class="col-xs-4 play-box last-right" id="5">
                              <div class="symbol"></div>
                          </div>
                          <div class="col-xs-4 play-box last-bottom" id="6">
                              <div class="symbol"></div>
                          </div>
                          <div class="col-xs-4 play-box last-bottom" id="7">
                              <div class="symbol"></div>
                          </div>
                          <div class="col-xs-4 play-box last-right last-bottom" id="8">
                              <div class="symbol"></div>
                          </div>
                      </div>
                      </div>
                  </div>
          
                  <div class="modal fade app-modal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
                    <div class="modal-dialog modal-size">
                      <div class="modal-content">
                        <h3 class="content heading">Warning!!!</h3>
                        <hr class="warning-hr">
                        <div class="content body">
                            Please save your time and don't even think you're smart. <br><strong><em>I'M SMARTER THAN YOU! HA-HA-HA!!!</em></strong> <br>
                            Wana try me? Chose : <br>
                            <div class="center-block symbol-options">
                              <button class="symbol-option btn btn-default btn-md" data-dismiss="modal">X</button> OR <button class="symbol-option btn btn-default btn-md" data-dismiss="modal">O</button>
                            </div>
                        </div>
                      </div>
                    </div>
                  </div>
          <script src="../js/bundled/tictactoe.bundled.js">
                  </script>
              </body>
          </html>

          4.創建一個JavaScript倒數計時器開始停止重置



          許多現代網站和博客都使用倒數計時器來顯示倒數,例如,我們通過使用倒數計時器來告訴在線商店的訪問者,商品價格將在價格上漲后增加銷售量。具體時間。

          <!DOCTYPE html>
          <html lang="zh">
          <head>
          <meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <meta http-equiv="X-UA-Compatible" content="ie=edge" />
          <title>CSS創建垂直時間軸(里程碑)</title>
          <style type="text/css">
           /* Variabes */  
          $orange: #ffa600;
          $grey:#f3f3f3;
          $white: #fff;
          $base-color:$orange ;
          
          
          /* Mixin's */  
          @mixin transition {
          -webkit-transition: all 0.5s ease-in-out;
          -moz-transition: all 0.5s ease-in-out;
          transition: all 0.5s ease-in-out;
          }
          @mixin corners ($radius) {
          -moz-border-radius: $radius;
          -webkit-border-radius: $radius;
          border-radius: $radius; 
          -khtml-border-radius: $radius; 
          }
          
          body {
          background:$base-color;
          font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; 
          height:100%;
          }
          
          .wrapper {
          width: 800px;
          margin: 30px auto;
          color:$white;
          text-align:center;
          }
          
          h1, h2, h3 {
            font-family: 'Roboto', sans-serif;
            font-weight: 100;
            font-size: 2.6em;
            text-transform: uppercase;
          }
          
          #seconds, #tens{
            font-size:2em;
          }
          
          button{
          @include corners (5px);
          background:$base-color;
          color:$white;
          border: solid 1px $white;
          text-decoration:none;
          cursor:pointer;
          font-size:1.2em;
          padding:18px 10px;
          width:180px;
          margin: 10px;
           outline: none;
            &:hover{
              @include transition;
              background:$white;
              border: solid 1px $white;
              color:$base-color;
              }
          } 
          </style>
              </head>
          <body>
          <div class="wrapper">
          <h1>Stopwatch</h1>
          <h2>Vanilla JavaScript Stopwatch</h2>
          <p><span id="seconds">00</span>:<span id="tens">00</span></p>
          <button id="button-start">Start</button>
          <button id="button-stop">Stop</button>
          <button id="button-reset">Reset</button>
          </div> 
          <script type="text/javascript">
            window.onload=function () {
            
            var seconds=00; 
            var tens=00; 
            var appendTens=document.getElementById("tens")
            var appendSeconds=document.getElementById("seconds")
            var buttonStart=document.getElementById('button-start');
            var buttonStop=document.getElementById('button-stop');
            var buttonReset=document.getElementById('button-reset');
            var Interval ;
          
            buttonStart.onclick=function() {
              
               clearInterval(Interval);
               Interval=setInterval(startTimer, 10);
            }
            
              buttonStop.onclick=function() {
                 clearInterval(Interval);
            }
            
          
            buttonReset.onclick=function() {
               clearInterval(Interval);
              tens="00";
              seconds="00";
              appendTens.innerHTML=tens;
              appendSeconds.innerHTML=seconds;
            }
            
             
            
            function startTimer () {
              tens++; 
              
              if(tens < 9){
                appendTens.innerHTML="0" + tens;
              }
              
              if (tens > 9){
                appendTens.innerHTML=tens;
                
              } 
              
              if (tens > 99) {
                console.log("seconds");
                seconds++;
                appendSeconds.innerHTML="0" + seconds;
                tens=0;
                appendTens.innerHTML="0" + 0;
              }
              
              if (seconds > 9){
                appendSeconds.innerHTML=seconds;
              }
            
            }<script src="../js/bundled/tictactoe.bundled.js">
                  </script>
          
          }
          
           </script>
              </body>
          </html>

          5.用JavaScript創建一個簡單的乒乓球游戲



          我可以用JavaScript構建游戲嗎?答案是肯定的,使用javascript甚至可以創建復雜的游戲,但是在這種情況下,我們將專注于一個簡單的游戲,該游戲可讓您練習HTML CSS和javascript技能。

          <!DOCTYPE html>
          <html lang="zh">
          <head>
          <meta charset="UTF-8" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <meta http-equiv="X-UA-Compatible" content="ie=edge" />
          <title>使用js調用設備攝像頭并實現拍照</title>
          <style type="text/css">
            body {
              text-align: center;
          }
            </style>
          </head>
          <body>
              <script type="text/javascript">
                // Global Variables
          var DIRECTION={
              IDLE: 0,
              UP: 1,
              DOWN: 2,
              LEFT: 3,
              RIGHT: 4
          };
          
          var rounds=[5, 5, 3, 3, 2];
          var colors=['#1abc9c', '#2ecc71', '#3498db', '#e74c3c', '#9b59b6'];
          
          // The ball object (The cube that bounces back and forth)
          var Ball={
              new: function (incrementedSpeed) {
                  return {
                      width: 18,
                      height: 18,
                      x: (this.canvas.width / 2) - 9,
                      y: (this.canvas.height / 2) - 9,
                      moveX: DIRECTION.IDLE,
                      moveY: DIRECTION.IDLE,
                      speed: incrementedSpeed || 9
                  };
              }
          };
          
          // The paddle object (The two lines that move up and down)
          var Paddle={
              new: function (side) {
                  return {
                      width: 18,
                      height: 70,
                      x: side==='left' ? 150 : this.canvas.width - 150,
                      y: (this.canvas.height / 2) - 35,
                      score: 0,
                      move: DIRECTION.IDLE,
                      speed: 10
                  };
              }
          };
          
          var Game={
              initialize: function () {
                  this.canvas=document.querySelector('canvas');
                  this.context=this.canvas.getContext('2d');
          
                  this.canvas.width=1400;
                  this.canvas.height=1000;
          
                  this.canvas.style.width=(this.canvas.width / 2) + 'px';
                  this.canvas.style.height=(this.canvas.height / 2) + 'px';
          
                  this.player=Paddle.new.call(this, 'left');
                  this.paddle=Paddle.new.call(this, 'right');
                  this.ball=Ball.new.call(this);
          
                  this.paddle.speed=8;
                  this.running=this.over=false;
                  this.turn=this.paddle;
                  this.timer=this.round=0;
                  this.color='#2c3e50';
          
                  Pong.menu();
                  Pong.listen();
              },
          
              endGameMenu: function (text) {
                  // Change the canvas font size and color
                  Pong.context.font='50px Courier New';
                  Pong.context.fillStyle=this.color;
          
                  // Draw the rectangle behind the 'Press any key to begin' text.
                  Pong.context.fillRect(
                      Pong.canvas.width / 2 - 350,
                      Pong.canvas.height / 2 - 48,
                      700,
                      100
                  );
          
                  // Change the canvas color;
                  Pong.context.fillStyle='#ffffff';
          
                  // Draw the end game menu text ('Game Over' and 'Winner')
                  Pong.context.fillText(text,
                      Pong.canvas.width / 2,
                      Pong.canvas.height / 2 + 15
                  );
          
                  setTimeout(function () {
                      Pong=Object.assign({}, Game);
                      Pong.initialize();
                  }, 3000);
              },
          
              menu: function () {
                  // Draw all the Pong objects in their current state
                  Pong.draw();
          
                  // Change the canvas font size and color
                  this.context.font='50px Courier New';
                  this.context.fillStyle=this.color;
          
                  // Draw the rectangle behind the 'Press any key to begin' text.
                  this.context.fillRect(
                      this.canvas.width / 2 - 350,
                      this.canvas.height / 2 - 48,
                      700,
                      100
                  );
          
                  // Change the canvas color;
                  this.context.fillStyle='#ffffff';
          
                  // Draw the 'press any key to begin' text
                  this.context.fillText('Press any key to begin',
                      this.canvas.width / 2,
                      this.canvas.height / 2 + 15
                  );
              },
          
              // Update all objects (move the player, paddle, ball, increment the score, etc.)
              update: function () {
                  if (!this.over) {
                      // If the ball collides with the bound limits - correct the x and y coords.
                      if (this.ball.x <=0) Pong._resetTurn.call(this, this.paddle, this.player);
                      if (this.ball.x >=this.canvas.width - this.ball.width) Pong._resetTurn.call(this, this.player, this.paddle);
                      if (this.ball.y <=0) this.ball.moveY=DIRECTION.DOWN;
                      if (this.ball.y >=this.canvas.height - this.ball.height) this.ball.moveY=DIRECTION.UP;
          
                      // Move player if they player.move value was updated by a keyboard event
                      if (this.player.move===DIRECTION.UP) this.player.y -=this.player.speed;
                      else if (this.player.move===DIRECTION.DOWN) this.player.y +=this.player.speed;
          
                      // On new serve (start of each turn) move the ball to the correct side
                      // and randomize the direction to add some challenge.
                      if (Pong._turnDelayIsOver.call(this) && this.turn) {
                          this.ball.moveX=this.turn===this.player ? DIRECTION.LEFT : DIRECTION.RIGHT;
                          this.ball.moveY=[DIRECTION.UP, DIRECTION.DOWN][Math.round(Math.random())];
                          this.ball.y=Math.floor(Math.random() * this.canvas.height - 200) + 200;
                          this.turn=null;
                      }
          
                      // If the player collides with the bound limits, update the x and y coords.
                      if (this.player.y <=0) this.player.y=0;
                      else if (this.player.y >=(this.canvas.height - this.player.height)) this.player.y=(this.canvas.height - this.player.height);
          
                      // Move ball in intended direction based on moveY and moveX values
                      if (this.ball.moveY===DIRECTION.UP) this.ball.y -=(this.ball.speed / 1.5);
                      else if (this.ball.moveY===DIRECTION.DOWN) this.ball.y +=(this.ball.speed / 1.5);
                      if (this.ball.moveX===DIRECTION.LEFT) this.ball.x -=this.ball.speed;
                      else if (this.ball.moveX===DIRECTION.RIGHT) this.ball.x +=this.ball.speed;
          
                      // Handle paddle (AI) UP and DOWN movement
                      if (this.paddle.y > this.ball.y - (this.paddle.height / 2)) {
                          if (this.ball.moveX===DIRECTION.RIGHT) this.paddle.y -=this.paddle.speed / 1.5;
                          else this.paddle.y -=this.paddle.speed / 4;
                      }
                      if (this.paddle.y < this.ball.y - (this.paddle.height / 2)) {
                          if (this.ball.moveX===DIRECTION.RIGHT) this.paddle.y +=this.paddle.speed / 1.5;
                          else this.paddle.y +=this.paddle.speed / 4;
                      }
          
                      // Handle paddle (AI) wall collision
                      if (this.paddle.y >=this.canvas.height - this.paddle.height) this.paddle.y=this.canvas.height - this.paddle.height;
                      else if (this.paddle.y <=0) this.paddle.y=0;
          
                      // Handle Player-Ball collisions
                      if (this.ball.x - this.ball.width <=this.player.x && this.ball.x >=this.player.x - this.player.width) {
                          if (this.ball.y <=this.player.y + this.player.height && this.ball.y + this.ball.height >=this.player.y) {
                              this.ball.x=(this.player.x + this.ball.width);
                              this.ball.moveX=DIRECTION.RIGHT;
          
                              beep1.play();
                          }
                      }
          
                      // Handle paddle-ball collision
                      if (this.ball.x - this.ball.width <=this.paddle.x && this.ball.x >=this.paddle.x - this.paddle.width) {
                          if (this.ball.y <=this.paddle.y + this.paddle.height && this.ball.y + this.ball.height >=this.paddle.y) {
                              this.ball.x=(this.paddle.x - this.ball.width);
                              this.ball.moveX=DIRECTION.LEFT;
          
                              beep1.play();
                          }
                      }
                  }
          
                  // Handle the end of round transition
                  // Check to see if the player won the round.
                  if (this.player.score===rounds[this.round]) {
                      // Check to see if there are any more rounds/levels left and display the victory screen if
                      // there are not.
                      if (!rounds[this.round + 1]) {
                          this.over=true;
                          setTimeout(function () { Pong.endGameMenu('Winner!'); }, 1000);
                      } else {
                          // If there is another round, reset all the values and increment the round number.
                          this.color=this._generateRoundColor();
                          this.player.score=this.paddle.score=0;
                          this.player.speed +=0.5;
                          this.paddle.speed +=1;
                          this.ball.speed +=1;
                          this.round +=1;
          
                          beep3.play();
                      }
                  }
                  // Check to see if the paddle/AI has won the round.
                  else if (this.paddle.score===rounds[this.round]) {
                      this.over=true;
                      setTimeout(function () { Pong.endGameMenu('Game Over!'); }, 1000);
                  }
              },
          
              // Draw the objects to the canvas element
              draw: function () {
                  // Clear the Canvas
                  this.context.clearRect(
                      0,
                      0,
                      this.canvas.width,
                      this.canvas.height
                  );
          
                  // Set the fill style to black
                  this.context.fillStyle=this.color;
          
                  // Draw the background
                  this.context.fillRect(
                      0,
                      0,
                      this.canvas.width,
                      this.canvas.height
                  );
          
                  // Set the fill style to white (For the paddles and the ball)
                  this.context.fillStyle='#ffffff';
          
                  // Draw the Player
                  this.context.fillRect(
                      this.player.x,
                      this.player.y,
                      this.player.width,
                      this.player.height
                  );
          
                  // Draw the Paddle
                  this.context.fillRect(
                      this.paddle.x,
                      this.paddle.y,
                      this.paddle.width,
                      this.paddle.height
                  );
          
                  // Draw the Ball
                  if (Pong._turnDelayIsOver.call(this)) {
                      this.context.fillRect(
                          this.ball.x,
                          this.ball.y,
                          this.ball.width,
                          this.ball.height
                      );
                  }
          
                  // Draw the net (Line in the middle)
                  this.context.beginPath();
                  this.context.setLineDash([7, 15]);
                  this.context.moveTo((this.canvas.width / 2), this.canvas.height - 140);
                  this.context.lineTo((this.canvas.width / 2), 140);
                  this.context.lineWidth=10;
                  this.context.strokeStyle='#ffffff';
                  this.context.stroke();
          
                  // Set the default canvas font and align it to the center
                  this.context.font='100px Courier New';
                  this.context.textAlign='center';
          
                  // Draw the players score (left)
                  this.context.fillText(
                      this.player.score.toString(),
                      (this.canvas.width / 2) - 300,
                      200
                  );
          
                  // Draw the paddles score (right)
                  this.context.fillText(
                      this.paddle.score.toString(),
                      (this.canvas.width / 2) + 300,
                      200
                  );
          
                  // Change the font size for the center score text
                  this.context.font='30px Courier New';
          
                  // Draw the winning score (center)
                  this.context.fillText(
                      'Round ' + (Pong.round + 1),
                      (this.canvas.width / 2),
                      35
                  );
          
                  // Change the font size for the center score value
                  this.context.font='40px Courier';
          
                  // Draw the current round number
                  this.context.fillText(
                      rounds[Pong.round] ? rounds[Pong.round] : rounds[Pong.round - 1],
                      (this.canvas.width / 2),
                      100
                  );
              },
          
              loop: function () {
                  Pong.update();
                  Pong.draw();
          
                  // If the game is not over, draw the next frame.
                  if (!Pong.over) requestAnimationFrame(Pong.loop);
              },
          
              listen: function () {
                  document.addEventListener('keydown', function (key) {
                      // Handle the 'Press any key to begin' function and start the game.
                      if (Pong.running===false) {
                          Pong.running=true;
                          window.requestAnimationFrame(Pong.loop);
                      }
          
                      // Handle up arrow and w key events
                      if (key.keyCode===38 || key.keyCode===87) Pong.player.move=DIRECTION.UP;
          
                      // Handle down arrow and s key events
                      if (key.keyCode===40 || key.keyCode===83) Pong.player.move=DIRECTION.DOWN;
                  });
          
                  // Stop the player from moving when there are no keys being pressed.
                  document.addEventListener('keyup', function (key) { Pong.player.move=DIRECTION.IDLE; });
              },
          
              // Reset the ball location, the player turns and set a delay before the next round begins.
              _resetTurn: function(victor, loser) {
                  this.ball=Ball.new.call(this, this.ball.speed);
                  this.turn=loser;
                  this.timer=(new Date()).getTime();
          
                  victor.score++;
                  beep2.play();
              },
          
              // Wait for a delay to have passed after each turn.
              _turnDelayIsOver: function() {
                  return ((new Date()).getTime() - this.timer >=1000);
              },
          
              // Select a random color as the background of each level/round.
              _generateRoundColor: function () {
                  var newColor=colors[Math.floor(Math.random() * colors.length)];
                  if (newColor===this.color) return Pong._generateRoundColor();
                  return newColor;
              }
          };
          
          var Pong=Object.assign({}, Game);
          Pong.initialize();
              </script>
          </body>
          </html>

          本篇未完結,請繼續看下一篇:手把手教你7個有趣的JavaScript 項目-下「附源碼」


          推薦JavaScript經典實例學習資料文章

          《JavaScript 使用 mediaDevices API 訪問攝像頭自拍》


          主站蜘蛛池模板: 中文字幕在线观看一区| 人妻视频一区二区三区免费 | 久久精品国产免费一区| 久久久久人妻一区二区三区vr| 精品国产区一区二区三区在线观看| 久久99国产精品一区二区| 午夜在线视频一区二区三区 | 精品亚洲一区二区三区在线观看| 男女久久久国产一区二区三区| 亚洲国产一区二区三区| 影院成人区精品一区二区婷婷丽春院影视| 一区二区三区日本电影| 在线日产精品一区| 中文字幕在线看视频一区二区三区| 激情内射亚州一区二区三区爱妻| 久久精品成人一区二区三区| 夜夜添无码一区二区三区| 精品福利一区3d动漫| 精品一区二区三区视频 | 一区二区精品视频| 高清一区二区三区视频| 亚洲福利一区二区精品秒拍| 国产成人精品第一区二区| 91在线一区二区| 精品乱子伦一区二区三区| 国偷自产av一区二区三区| 中文字幕色AV一区二区三区| 91精品福利一区二区| 亚洲综合无码一区二区| 国产激情一区二区三区 | 波多野结衣一区在线观看| 久久国产午夜精品一区二区三区| 精品国产一区二区麻豆| 国产成人一区二区三区在线观看| 精品久久一区二区三区| 色欲AV蜜桃一区二区三| 国产精品毛片一区二区| 精品一区二区三区在线观看l| 91精品乱码一区二区三区| 国产精品一区二区久久| 精品爆乳一区二区三区无码av|