JS - 使用 javascript 自定义 html select 控件

JS - Customising html select control using javascript

如何自定义具有多个选项的 select 元素,例如 Select Element to Button element?是否可以使用 JS 实现按钮作为选择选项的一种方式?

第一个元素由 Prestashop 及其部分产品功能生成。

编辑:我不知道 Prestashop,但如果您可以编辑 JS 或将 JS 实现到代码中,这可能会有所帮助。

如果您真的想更改 select 元素,这会对您有所帮助。 我会建议以不同的方式来做,但这是你的选择。

HTML(注意我禁用了 select 所以用户将无法更改):

<div class="wrapper">
<div id="minusBtn">-</div>
<select id="mySelect" disabled>
  <option value="1">option1</option>
  <option value="2">option2</option>
  <option value="3">option3</option>
  <option value="4">option4</option>
  <option value="5">option5</option>
</select>
<div id="plusBtn">+</div>
</div>

CSS:

.wrapper{
  display:flex;
}
select{
   -webkit-appearance: none;
  
}
/*style the disabled select*/
select[disabled] {
  border:1px solid black !important;
  opacity:1;
  color:black;
  width:60px;
  height:20px;
  
}
#plusBtn, #minusBtn{
  cursor:pointer;
    height:20px;
  text-align:center;
  width:15px;
  border:1px solid black;
}

JS:

var count = 1

document.getElementById('plusBtn').addEventListener('click', function(){
  //first check if count is less than the max options length
  if(count < document.getElementById("mySelect").options.length){
    //increase count by 1
    count++
    //changing the select option to count
    document.getElementById('mySelect').value = count
  
    } else{
      //if count is more than the options length we want to give the last option
      document.getElementById('mySelect').value = 5
    }
 })

document.getElementById('minusBtn').addEventListener('click', function(){
  if(count > 1){
    count--
  document.getElementById('mySelect').value = count
  
    } else{
      document.getElementById('mySelect').value = 1
    }
 })


当然,用户可以使用开发人员工具检查页面并将 HTML 更改为 select。 在这种情况下,您必须进行后端验证。

代码笔:https://codepen.io/Elnatan/pen/RwabNBv


我根据 Mad SQL 的回答编辑了 JS 代码。 所以因为现在我们将使用 selectedIndex,计数应该等于 0 而不是 1,因为索引从 0 开始。 我将 selected 索引与选项的长度进行比较(如果它处于最大值),所以现在它应该可以工作,即使您将从 select.

添加或删除选项

所以现在它应该是这样的:(我没有添加 getProductAttribute())

var count = 0
var selectLength = document.getElementById("mySelect").options.length

document.getElementById('plusBtn').addEventListener('click', function(){
    //increase count by 1
    count++
  //check if count is less than the max options length
  if(count < document.getElementById("mySelect").options.length){
    
    //changing the select option to count
    document.getElementById('mySelect').selectedIndex  = count
  
    } else{
      //if count is more than the options length we want to give the last option
      count = selectLength
      document.getElementById('mySelect').selectedIndex = selectLength -1
    }
 })

document.getElementById('minusBtn').addEventListener('click', function(){
    count--
  if(count > 0){
    
  document.getElementById('mySelect').selectedIndex = count
  
    } else{
    count = 0
      document.getElementById('mySelect').selectedIndex = 0
    }
 })