Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - How do I use css to change the font of a select option?

I create the HTML for a SELECT list (it's not a dropdown!) and its OPTIONs through Java (8):

static final String font="style="font-family: 'Courier New'"";
out.println("<SELECT name='l' id='selectList' size=19 style='width: 400px'>
");
out.println("<OPTION value='"+value+"' "+font+" >"+someText+"</OPTION>");

The HTML then looks like this:

<SELECT name='l' id='selectList' size=19 style='width: 400px'>
<OPTION value='0' style="font-family: 'Courier New'" >Some Text</OPTION>

Next to the list there's also an "Append" button that appends more elements through JavaScript:

var selectList = document.getElementById("selectList");
var option = new Option(mytext,myvalue);
selectList.appendChild(option);

Problem: This new option doesn't use the "Courier New" font.

My "styles.css" file already has a custom "h3" and "h4" but I now also want to create a custom "substyle" that I can then set the option in both HTML and Javascript to. Padding, font size,... should all be the default, I only want to set the font-family of these specific options to "Courier New" and do it in a way that if I want to change it again later on, I only have to do it in a single spot (the css). This style should only affect the options I use it on, the others should all use the default style or whatever I set them to.

Question: How do I accomplish this (without adding an extra library)?

I'm aware there are already a bunch of questions asking similar things but they're usually at least 5 years old, some refer to dropdowns and some even say that it's not possible to change what an option looks like, which changed in the last couple of years.

What I've tried:

Java/HTML:

out.println("<OPTION value='"+value+"' "+"class="somethingsomething""+" >"+someText+"</OPTION>");
//<OPTION value='0' class="somethingsomething" >Some Text</OPTION> //Result

CSS:

.somethingsomething { //Also tried "option.somethingsomething"
    font-family: 'Courier New', monospace;
}

This doesn't seem to work (tested with Firefox), the options use the default font.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...