當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


p5.js Element toggleClass()用法及代碼示例

p5.j​​s中p5.Element的toggleClass()用於切換元素中的指定類。類的切換意味著將根據當前狀態添加或刪除該類。

用法:

toggleClass(class)

參數:該函數接受如上所述和以下描述的單個參數:

  • class:它是一個字符串,表示要切換的類。

以下示例說明了p5.js中的toggleClass()方法。

例:以下HTML代碼顯示了必須為類添加的CSS樣式才能顯示其效果。 p5.j​​s元素現在可以使用這些類。



HTML

<!DOCTYPE html> 
<html> 
  
<head> 
    <script src= 
"https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.js"> 
    </script> 
  
    <script src="sketch.js"></script> 
  
    <style> 
        .red { 
            background-color:red; 
        } 
  
        .border { 
            border:10px dashed; 
        } 
    </style> 
</head> 
  
<body></body> 
  
</html>

JavaScript代碼:“sketch.js”文件包含演示此方法的p5.js代碼。

Javascript

function setup() { 
  canv = createCanvas(550, 300); 
  textSize(18); 
  
  text("Click on the buttons to toggle the " + 
       "given class of the canvas", 20, 30); 
  
  setBtn = createButton("Toggle Color"); 
  setBtn.position(30, 60); 
  setBtn.mouseClicked(toggleColor); 
  
  setBtn = createButton("Toggle Border"); 
  setBtn.position(160, 60); 
  setBtn.mouseClicked(toggleBorder); 
  
  canv.addClass("red"); 
  canv.addClass("border"); 
} 
  
function toggleColor() { 
  clear(); 
  
  // Toggle the given class 
  canv.toggleClass("red"); 
  text("The color class has been toggled", 30, 120); 
  text("Click on the buttons to toggle the " + 
       "given class of the canvas", 20, 30); 
} 
  
function toggleBorder() { 
  clear(); 
  
  // Toggle the given class 
  canv.toggleClass("border"); 
  text("The border class has been toggled", 30, 120); 
  
  text("Click on the buttons to toggle the " + 
       "given class of the canvas", 20, 30); 
}

輸出:

在線編輯: https://editor.p5js.org/
環境設置: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
參考: https://p5js.org/reference/#/p5.Element/toggleClass

相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 p5.js Element toggleClass() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。