首页 > 解决方案 > 选择没有下拉选项的标签

问题描述

我正在尝试创建一个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(以及任何脚本,如果可能的话)来实现吗?

标签: javascriptjqueryhtmlcss

解决方案


- 仅 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>


推荐阅读