简体   繁体   English

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

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

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

Here is a simple example: 这是一个简单的示例:

The HTML: HTML:

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

The Javascript: 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
};

User below select and add options as per you requirement. 下面的用户根据您的要求选择并添加选项。

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

Below script is used to change background color of the webpage, you can change to a specific DOM element. 下面的脚本用于更改网页的背景色,您可以更改为特定的DOM元素。

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

Well first you would probably want to add an id to the body tag, for easy reference from javascript. 首先,您可能想向body标签添加一个id,以便从javascript轻松参考。 You would then attach an event handler to the onChange event of the dropdown (select) input, using a color name as the value, and pass that to the event handler. 然后,您将使用颜色名称作为值,将事件处理程序附加到下拉(选择)输入的onChange事件上,并将其传递给事件处理程序。 In the event handler you will then change the color of the background (grabbing it by its ID, using either jQuery or vanilla js) to whatever string color value was passed. 然后,在事件处理程序中,您将更改背景色(使用jQuery或vanilla js通过其ID抓取背景)为传递的任何字符串颜色值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM