gpt4 book ai didi

javascript - 一个函数有多个对象事件?

转载 作者:行者123 更新时间:2023-12-03 02:04:06 25 4
gpt4 key购买 nike

所以我正在尝试制作一个带有 3 个背景 slider (R、G、B)的 html 页面

我希望每个 slider 调用一个更改输入背景的函数,但除非我为每个事件重写该函数,否则我无法让它工作。请耐心等待,我是一名新程序员,其中大部分内容都是意大利面条

var red = document.getElementById("red"); //slider values
var routput = document.getElementById("reddemo"); //display values
routput.innerHTML = red.value; //for function

var green = document.getElementById("green");
var goutput = document.getElementById("greendemo");
goutput.innerHTML = green.value;

var blue = document.getElementById("blue");
var boutput = document.getElementById("bluedemo");
boutput.innerHTML = blue.value;

red.oninput && blue.oninput && green.oninput = function() {
//this is what I want to do; string all of these oninputs together... obviously this way doesn't work
var x = Math.round([Number(red.value) + Number(blue.value) + Number(green.value)] / 3);
//this is for later, the text color in body changes to white when color values get too low

routput.innerHTML = Math.round(this.value);
boutput.innerHTML = Math.round(this.value);
goutput.innerHTML = Math.round(this.value);

document.body.style.backgroundColor = "rgb(" + routput.innerHTML + "," + routput.innerHTML + "," + routput.innerHTML + ")";

if (x < 127.5) {
document.body.style.color = "rgb(255,255,255)";
} else {
document.body.style.color = "rgb(0,0,0)";
}
}
<p>Red</p>
<div class="slidecontainer">
<input type="range" min="0" max="255" value="255" class="slider" id="red">
<p>Value: <span id="reddemo"></span></p>
</div>
<p>Green</p>
<div class="slidecontainer">
<input type="range" min="0" max="255" value="255" class="slider" id="green">
<p>Value: <span id="greendemo"></span></p>
</div>
<p>Blue</p>
<div class="slidecontainer">
<input type="range" min="0" max="255" value="255" class="slider" id="blue">
<p>Value: <span id="bluedemo"></span></p>
</div>

最佳答案

JavaScript 中的函数是一等公民,这意味着您可以将函数视为变量:

var changeBackground = function () {…};

red.oninput = changeBackground;
blue.oninput = changeBackground;

关于javascript - 一个函数有多个对象事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49882937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com