简体   繁体   中英

Make the first option in a select element a selectable placeholder

I have a select element in HTML and I would like to give it a placeholder. I want this placeholder to be selectable (so no options are selected).

Because it is a placeholder I want the option text to be grey, and when the option is selected I want the select element's text to also be grey.

There are many questions that solve part of this problem, but none that offer a functional solution (that I can find).

Below is an example of the desired outcome (see the Campus dropdown).

示例图像。

I am using React for the project, and have looked at the React-select package but cannot find a way to implement it like this.

You can do this with CSS by making the option color grey with a selector, making the select grey when the default is selected, , and making other options a specific color (so they remain that color when the select is grey rather than inheriting grey from it). Here's an example:

 const {useState} = React; function Example() { const [value, setValue] = useState(""); const onChange = ({currentTarget: {value}}) => { setValue(value); }; return <select size="1" className={value ? "" : "greyed"} value={value} onChange={onChange}> <option value="">Default</option> <option value="A">Option A</option> <option value="B">Option B</option> </select>; } ReactDOM.render(<Example/>, document.getElementById("root"));
 /* We have this so that when the select is greyed, its options aren't */ select option[value] { color: black; } /* Grey-out an element with the class, and option elements with blank values */ .greyed, select option[value=""] { color: grey; }
 <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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