javascript - 选择没有下拉选项的标签
问题描述
我正在尝试创建一个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>
推荐阅读
- sql-server - 在 SQL Server Management Studio 中使用 BULK INSERT 出现“传输级错误”
- visual-studio-code - 是否有用于从选定或剪贴板代码创建新文件的 VS Code 快捷方式?
- python-3.x - pandas.read_csv 仅在一列中返回不可读的文本
- reactjs - 使用钩子获取数据时的意外行为
- python - Python 返回值的开始/停止索引
- spring-boot - 尝试访问 putmapping url 时禁止响应
- php - 如何更改表格内容而不是转到目录
- javascript - 更改 'Window.location.href' 时删除存储在 'window' 对象上的属性
- scala - 使用 doobie 阅读
- php - Wordpress Customizer 不断隐藏自定义部分