p5.js 元素 toggleClass() 方法
p5.js 中 p5.Element 的toggleClass()用于切换元素中的指定类。类的切换意味着它将根据当前状态添加或删除。
句法:
toggleClass(class)
参数:此函数接受如上所述和如下所述的单个参数:
- class:它是一个字符串,表示要切换的类。
下面的示例说明了 p5.js 中的toggleClass()方法。
示例:以下 HTML 代码显示了必须为类添加的 CSS 样式以显示其效果。 p5.js 元素现在可以使用这些类。
HTML
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);
}
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