Can you have multiple lines in an

2019-01-09 06:39发布

Is there a way to have multiple lines in an <option> element?

Like this:

 -------------------------
| Normal <option> element |
 -------------------------
| <option> element broken |
| onto two lines          |
 -------------------------
| Normal <option> element |
 -------------------------

Is there any HTML/CSS approach, or should I use JavaScript?

5条回答
我命由我不由天
2楼-- · 2019-01-09 07:16

It's a particular case of displaying HTML tags inside an <option></option> element. As far as I know, browsers behave very differently in this area (Firefox displays even images, other browsers ignore most or all tags) and there isn't a cross-browser solution. You'll probably need to emulate it with JavaScript and a different markup.

At http://www.w3.org/TR/2011/WD-html-markup-20110113/option.html they say:

Permitted contents: normal character data

... which is defined at http://www.w3.org/TR/2011/WD-html-markup-20110113/syntax.html#normal-character-data

The spec is hard to understand, as usual, but I understand that you cannot insert a literal < (i.e., an HTML tag such as <br>). I cannot find where it defines the behaviour with blank space but most browsers appear to collapse it.

查看更多
甜甜的少女心
3楼-- · 2019-01-09 07:29

This may not be what you want, but you can get two lines per option, by using the "optgroup" tag e.g:

<select>
  <optgroup label="Click below for 'yes'">
    <option value="yes">Yes</option>
  </optgroup>
  <optgroup label="Click below for 'No'">
    <option value="no">No</option>
  </optgroup>
</select>
查看更多
老娘就宠你
4楼-- · 2019-01-09 07:36

I’m afraid not. Browsers seem to ignore newline characters and HTML <br> tags inside <option> elements, and I don’t think JavaScript provides any way to manipulate how this text appears.

查看更多
欢心
5楼-- · 2019-01-09 07:41

The problem with select's is that they are OS form elements as opposed to web form elements. That's why it's not possible to style them in some browsers (cough... IE6) unlike other inputs. Have you seen an example of this anywhere? As the operating system doesn't accommodate this, the browser won't either.

I'd also point out that it's not very user friendly. Users are used to the idea of a select box containing options on single lines. If you start to put them on multiple lines, you are going against the grain of the select box's usability and inherent accessibility. It might not be such a good idea to take this route.

Just my opinion, but hope it makes sense.

查看更多
淡お忘
6楼-- · 2019-01-09 07:41

No, you'll have to build custom drop down list for such a thing.

jQuery offers lots of these; you can probably use CSS to define height for specific options to achieve what you need.

查看更多
登录 后发表回答