每当更改元素的值时,都会触发changed()函数。它可用于检测复选框元素或选择元素中的更改。它还可以用于将事件侦听器附加到元素。
用法:
changed(fxn)
参数:该函数接受如上所述和以下描述的单个参数。
- fxn:这是在检测到更改时将调用的回调函数。可以将其传递为“ false”,这将阻止先前的触发函数停止触发。
以下示例说明了p5.js中的changed()函数:
范例1:检测复选框元素中的更改
let red = 0;
let green = 0;
let blue = 0;
function setup() {
createCanvas(600, 300);
// create input boxes
redCheckbox = createCheckbox('Red', false);
redCheckbox.position(20, 40)
redCheckbox.changed(redChanged);
greenCheckbox = createCheckbox('Green', false);
greenCheckbox.position(100, 40)
greenCheckbox.changed(greenChanged);
blueCheckbox = createCheckbox('Blue', false);
blueCheckbox.position(180, 40)
blueCheckbox.changed(blueChanged);
}
function draw() {
clear()
// change the fill color based
// on current rgb the values
fill(red, green, blue);
rect(20, 80, 300, 300);
textSize(20);
text("Check the boxes to change the fill color", 10, 20);
}
// functions for each of the colors
function redChanged() {
if (this.checked())
red = 128;
else
red = 0;
}
function greenChanged() {
if (this.checked())
green = 128;
else
green = 0;
}
function blueChanged() {
if (this.checked())
blue = 128;
else
blue = 0;
}
输出:
范例2:检测选择元素中的更改
let red = 0;
let green = 0;
let blue = 0;
function setup() {
createCanvas(350, 300);
textSize(18)
text("Select the color to change the background color", 10, 20);
// create select element
selectElem = createSelect();
selectElem.position(20, 40);
selectElem.option('Slecet');
selectElem.option('Red');
selectElem.option('Green');
selectElem.option('Blue');
selectElem.changed(changeColor);
}
function changeColor() {
clear();
colorVal = this.value();
if (colorVal == "Red") {
background("red");
}
else if (colorVal == "Green") {
background("green");
}
else if (colorVal == "Blue") {
background("blue");
}
else
background(128);
text("Select the color to change the background color", 10, 20);
}
输出:
参考: https://p5js.org/reference/#/p5/changed
相关用法
- p5.js str()用法及代码示例
- PHP pi( )用法及代码示例
- d3.js d3.lab()用法及代码示例
- p5.js nf()用法及代码示例
- p5.js nfp()用法及代码示例
- d3.js d3.rgb()用法及代码示例
- p5.js int()用法及代码示例
- d3.js d3.map.set()用法及代码示例
- p5.js nfc()用法及代码示例
- p5.js hex()用法及代码示例
注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 p5.js | changed() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。