如何根据从选择菜单中提供给用户的选项更改网页的背景颜色

How can i change the background colour of a webpage based on options given to the user from a select menu?

本文关键字:选项 网页 颜色 背景 给用户 何根 选择 菜单      更新时间:2023-09-26

我想要一个下拉菜单,允许用户设置网页的背景颜色,我在网上搜索,似乎只找到了如何更改实际列表本身的背景,而我希望它更改整个表单的颜色。

这里有一个简单的例子:

HTML:

<body>
    <select id="color" name="color">
        <option value="red">Red</option>
        <option value="green">Green</option>
        <option value="blue">Blue</option>
    </select>
</body>

Javascript:

// grab the body and select
var body = document.body;
var select = document.getElementById( 'color' );
// listen for the select's change event
select.onchange = function() {
    var color = select.options[select.selectedIndex].value; // get the selected color
    body.style.background = color; // apply the selected color to the body
};

下面的用户根据您的要求选择并添加选项。

<select id="color-select">
<option value="red">Red</option>
<option value="green">Green</option>
</select>

以下脚本用于更改网页的背景颜色,您可以更改为特定的DOM元素。

document.getElementById('color-select').onchange = function () {
 document.body.style.backgroundColor = document.getElementById('color-select').value;
    };

首先,您可能希望在body标记中添加一个id,以便从javascript中轻松引用。然后,使用颜色名称作为值,将事件处理程序附加到下拉(选择)输入的onChange事件,并将其传递给事件处理程序。在事件处理程序中,您将更改背景的颜色(通过其ID获取背景,使用jQuery或vanilla-js)为传递的任何字符串颜色值。