我正在尝试创建一个没有下拉选项的 select
标签
我需要外观作为第一个输出(没有下拉列表)但只有一个选项,这样我就可以切换选项而无需拉出下拉列表。
我尝试为 select 标签设置高度,但它不起作用。
我的问题不是隐藏第一个元素,我不想拉出选项下拉列表,我需要切换选项。
/*.scrollable{height:25px;}*/
.scrollable{margin-right:25px;}
<select size="2" class="scrollable">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<select size="1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
仅使用 html 和 css(以及任何可能的脚本)是否有可能?
最佳答案
- 仅 HTML(半)解决方案
假设您想像示例中那样使用数字,您也可以使用数字类型的输入字段。
我添加了一些 CSS 以始终在 Chrome 中显示箭头。在其他浏览器中,箭头始终显示。
请注意,这仅适用于数字,不适用于字符串或其他类型。
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
opacity: 1;
}
<input value="1" min="1" max="9" type="number" style="width:30px"/>
- Javascript 解决方案
此解决方案涉及一些简单的 Javascript,但也适用于字符串。您可以设置 <div>
的样式无论您喜欢什么标签,它们都类似于向上和向下按钮,这由您决定。
var options = [ "Orange", "Kiwi", "Banana", "Strawberry", "Pear" ]
// The current index of the options array
var current = 0;
// This function removes 1 from the currently selected option index and sets the field value
function prev(){
if(current > 0) current--;
setFieldValue(options[current]);
}
// This function adds 1 to the currently selected option index and sets the field value
function next(){
if(current < options.length-1) current++;
setFieldValue(options[current]);
}
function setFieldValue(text){
document.getElementById("field").value = options[current];
}
// Call the method so the field doesn't start out empty
setFieldValue(options[current]);
div.button {
display: block;
position: absolute;
width: 20px;
height: 10px;
text-align: center;
background-color: gray;
color: white;
line-height: 10px;
cursor: pointer;
}
div.button:hover {
background-color: lightgray;
}
div.one {
right: 0;
top: 0;
}
div.two {
right: 0;
bottom:0;
}
div.field-wrapper {
display: inline-block;
position: relative;
}
input#field {
background-color: white;
}
<div class="field-wrapper">
<input id="field" disabled/>
<div class="button one" onclick="prev();">^</div>
<div class="button two" onclick="next();">v</div>
</div>
关于javascript - 选择没有下拉选项的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52056202/