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


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

p5.j​​s中p5.Element的hasClass()方法用於檢查元素中是否已存在指定的類。它返回一個布爾值,指示是否存在該類。一個元素可以分配多個類。

用法:

hasClass( class )

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

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

例:下麵的示例說明了p5.js中的hasClass()方法

<html> 
  
<head> 
    <script src= 
"https://cdn.jsdelivr.net/npm/p5@0.10.2/lib/p5.js"> 
    </script> 
    <script src="sketch.js"></script> 
</head> 
  
<body></body> 
  
</html>

Javascript代碼:以下代碼用於上述“sketch.js”文件。



Javascript

function setup() { 
  createCanvas(600, 300); 
  textSize(18); 
    
  // Create a new p5.Element 
  tmpElement = createElement("div"); 
  
  text("Click on the buttons to add, remove " + 
       "or check the class of the element", 20, 20); 
  
  setBtn =  
    createButton("Add color class to element"); 
    setBtn.position(30, 40); 
    setBtn.mouseClicked(() => { 
    tmpElement.addClass("color"); 
  }); 
  
  removeBtn = 
    createButton("Remove color class from element"); 
  removeBtn.position(30, 80); 
  removeBtn.mouseClicked(() => { 
    tmpElement.removeClass("color"); 
  }); 
  
  showBtn = createButton("Check if class exists"); 
  showBtn.position(30, 120); 
  showBtn.mouseClicked(checkClass); 
} 
  
function checkClass() { 
  clear(); 
  // Check if the given class exists 
  let hasC = tmpElement.hasClass("color"); 
  
  text("hasClass('color') gives the output:" + 
       hasC, 20, 180); 
  
  text("Click on the buttons to add, remove or " + 
       "check the class of the element", 20, 20); 
}

輸出:

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

相關用法


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