简体   繁体   English

选项的 HTML-CSS 背景颜色

[英]HTML-CSS Background color for option

I'm working on an option form.我正在处理一个选项表。 I want each option to have a different color on the scroll down and once an option is selected I want to save it, and display the selection and color.我希望每个选项在向下滚动时都有不同的颜色,一旦选择了一个选项,我想保存它,并显示选择和颜色。

在此处输入图片说明

What I want to be able to do is save the form, come back to the page and see the option I previously selected while displaying the color.我想要做的是保存表单,返回页面并查看我之前在显示颜色时选择的选项。 In the picture above 2020 shows an example of the options.在上图中 2020 显示了选项的示例。 What I want after I save the form is for my selection to appear (like in 2021) with the selection color(in this case 2021 is medium/yellow).保存表单后我想要的是让我的选择显示(如 2021 年)和选择颜色(在这种情况下 2021 年是中/黄色)。 What can I do so that the selected box option takes the color of the option in the scroll down?我该怎么做才能使选定的框选项在向下滚动中采用该选项的颜色? How can I save this so that the option remains selected the next time I visit the page?如何保存它以便下次访问该页面时该选项保持选中状态?

HTML HTML

<form action="" method="post">
{% csrf_token %}
        {% for year in years %}
        <select name="rating" id="{{year.id}}">
        <script src="{% static 'SCS/scripts/script.js' %}"/></script> 
            <option>Choose From List</option>
            <option class=green value="green">High</option>
            <option class=yellow value="yellow">Medium</option>
            <option class=orange value="orange">Low</option>
            <option class=gray value="gray">N/A</option>
        </select> 
            <input type="hidden" name="year" value={{year.fy_year}}>
        {% endfor %}
        <input id=save_cap type="submit" value="Save">
      </form>

CSS CSS

.green{
    background-color: green;
}

.yellow{
    background-color: yellow;
}

.orange{
    background-color: orangered;
}

.gray{
    background-color: gray;
}

You need some JavaScript to achieve your goals.你需要一些 JavaScript 来实现你的目标。

To do so that the selected box option takes the color of the option in the scroll down you can write:为此,所选框选项采用向下滚动中选项的颜色,您可以编写:

document.getElementById("rating").addEventListener("change", function() {
    this.className = this.value;
});

This code takes the selected option value and sets it as a class name of the select .此代码采用选定的选项值并将其设置为select的类名。 To make it work you have to add some values to your options:为了让它工作,你必须在你的选项中添加一些值:

<select name="rating" id="rating">
    <option class=white value="white">Choose From List</option>
    <option class=green value="green">High</option>
    <option class=yellow value="yellow">Medium</option>
    <option class=orange value="orange">Low</option>
    <option class=gray value="gray">N/A</option>
</select>

And to save the selected option you need localStorage :保存所选选项,您需要localStorage

let selected = localStorage.getItem("selected");
let rating = document.getElementById("rating");

if (selected) {
    rating.selectedIndex = selected;
    rating.className = rating.value;
}

rating.addEventListener("change", function() {
    localStorage.setItem("selected", this.selectedIndex);
    this.className = this.value;
});

Check the working JSFiddle .检查工作 JSFiddle

I'm used to jQuery so this has been a learning experience for me but I do have a solution for you.我习惯了 jQuery,所以这对我来说是一次学习经历,但我确实为您提供了解决方案。 I'll take you through my logic, and the snippet is below (possibly due to cookies I could only get it to work locally and on the w3 demo):我将带您了解我的逻辑,代码片段如下(可能由于 cookie,我只能让它在本地和 w3 演示中工作):

  1. Add values to the options: <option class="green" value="high">High</option> so we can retrieve them and store the values in a cookie向选项添加值: <option class="green" value="high">High</option>这样我们就可以检索它们并将值存储在 cookie 中

  2. Set a change event listener to change color, s being a : s.addEventListener( 'change', changeColor );设置change事件侦听器以更改颜色, s为: s.addEventListener( 'change', changeColor );

  3. Once we've changed the color with this.className += this.selectedOptions[0].className;一旦我们用this.className += this.selectedOptions[0].className;改变了颜色this.className += this.selectedOptions[0].className; more info here 更多信息在这里

  4. Then we can pass the information to a cookie with setCookie( this.id, this.value );然后我们可以使用setCookie( this.id, this.value );将信息传递给 cookie setCookie( this.id, this.value ); more info here更多信息在这里

  5. Now we've got changing colours and stored cookies, we need to be able to load any stored values on document ready , so here goes:现在我们已经改变了颜色并存储了 cookie,我们需要能够在文档就绪时加载任何存储的值,所以这里是:

     let cookie = getCookie ( `select-${s.id}` ); // if cookie is not empty, set selected option and change color if ( cookie != '' ) { s.value = cookie; s.className += s.selectedOptions[0].className; }

Now we have:现在我们有:

  • changing colour改变颜色
  • stored values存储值
  • loaded values加载值

There's definitely (in the other answer actually) a better, more concise way to do this, but I hope that some of the links will help you understand more about what's going on :)肯定(实际上在另一个答案中)有一种更好、更简洁的方法可以做到这一点,但我希望其中的一些链接能帮助您更多地了解正在发生的事情:)

 // set up onChange event listeners function setSelectOnChangeListeners() { // select all of your <select>'s const selects = document.getElementsByTagName("select"); // for each of your <select>'s for (s of selects) { // add an onChange event listener to trigger function changeColor(); s.addEventListener('change', changeColor); } } // on <select> onChange event, change color to selected option color based on class function changeColor() { // this is the interesting part, where you can return which item has been selected in your <select> console.log(`class = ${this.selectedOptions[0].className}`); // clear existing className, note that if you want to have a class on your select, you can set the below equal to that instead of '' this.className = ''; // set <select> className to the selected <option> className this.className += this.selectedOptions[0].className; // after we've changed the color, we'll change the cookie setCookie(this.id, this.value); } // set cookies with format "select-<id> = <val>" function setCookie(id, val) { // cookies are stored as key | value pairs document.cookie = `select-${ id } = ${ val }`; console.log(`cookie set with data ${id}, ${val}`); } // w3 get cookie method function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } // on document load document.addEventListener('DOMContentLoaded', function(event) { // for each select, try to load cookie data const selects = document.getElementsByTagName("select"); for (s of selects) { let id = s.id; let cookie = getCookie(`select-${s.id}`); // if cookie is not empty, set selected option and change color if (cookie != '') { s.value = cookie; s.className += s.selectedOptions[0].className; } } // set listeners setSelectOnChangeListeners(); });
 .green { background-color: green } .yellow { background-color: #ff0 } .orange { background-color: #ff4500 } .gray { background-color: gray }
 <select id="2020" name="rating"> <option>Choose From List</option> <option class="green" value="high">High</option> <option class="yellow" value="medium">Medium</option> <option class="orange" value="low">Low</option> <option class="gray" value="none">N/A</option> </select> <select id="2021" name="rating"> <option>Choose From List</option> <option class="green" value="high">High</option> <option class="yellow" value="medium">Medium</option> <option class="orange" value="low">Low</option> <option class="gray" value="none">N/A</option> </select>

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

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