[英]Is there a way to make user select a color/colour with only the option that you give them in JavaScript/HTML?
Hey I was wondering if there is a way that you can make the user choose a colour/color with the options that you give them?嘿,我想知道是否有一种方法可以让用户使用您提供的选项来选择颜色/颜色? I know there is a way to let user select a color/colour of thier choices but is there a way that you give the user only three options that change the background colour/color?我知道有一种方法可以让用户 select 选择颜色/颜色,但是有没有一种方法可以让用户只给用户三个改变背景颜色/颜色的选项? for instance let say I want the user to only have the choice between black and blue how would I code this?例如,假设我希望用户只能在黑色和蓝色之间进行选择,我将如何编写代码?
This is what I tried:这是我试过的:
HTML Page: HTML 页:
<div class="colour selector">
Pick a color <input onchange="colorSelected(this)" type="color">
</div>
JavaScript Page: JavaScript 页:
function colorSelected (element) {
document.body.style.background = element.value
}
But i want to be able to give the user limted options like only three colours (red, blue & yellow)但我希望能够为用户提供有限的选项,比如只有三种颜色(红色、蓝色和黄色)
let select = document.getElementById("select"); let text = document.getElementById("text"); select.onclick = function() { switch (select.value){ case "red": text.style.color = "red"; select.style.backgroundColor = "red"; break; case "pink": text.style.color = "pink"; select.style.backgroundColor = "pink"; break; case "blue": text.style.color = "blue"; select.style.backgroundColor = "blue"; break; } }
.color1{ background-color:red; }.color2{ background-color:pink; }.color3{ background-color:blue; }
<select id="select"> <option hidden selected value="">Choose a color</option> <option value="red" class="color color1"></option> <option value="pink" class="color color2"></option> <option value="blue" class="color color3"></option> </select> <p id="text">Some text</p>
Edited version编辑版本
Use a select with option for each choice.使用 select 和每个选项的选项。
Use your function in an eventListener that will pass the event object as an argument so you can get the value from the select (which is the event.target
):在将事件 object 作为参数传递的 eventListener 中使用您的 function,以便您可以从 select(即event.target
)获取值:
const mySelect = document.getElementById("my-select"); mySelect.addEventListener("change", colorSelected); function colorSelected(event) { document.body.style.background = event.target.value }
<select id="my-select"> <option value="pick" hidden>Pick a color</option> <option value="red">Red</option> <option value="blue">Blue</option> <option value="yellow">Yellow</option> </select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.