html-js, realize the trigger event when the option specified in select is selected

HTML

 <input type="text" class="text" name="">
       <!-- 在下拉列表中,一般在select上做响应 -->
       <!-- 我们在用到下拉列表框select时,需要对选中的选项触发事件,
       其实option本身没有触发事件方法,我们只有在select里的onchange方法里触发 -->
       <select name="col" id="choice" onclick="changeColor()">
           <option value="">请选择颜色</option>
           <option value="red">红</option>
           <option value="yellow">黄</option>
           <option value="blue">蓝</option>
           <option value="green">绿</option>
       </select>

JS

<script>
           var text = document.querySelector('.text')
           function changeColor(){
        //(获取value) 方法一:
            //   var choice = document.querySelector('#choice')
            //   使用selectedIndex属性获取当前选项的索引
            //   var index =  choice.selectedIndex
            //   获取select中指定点击的option上的value值
            //   var color =  choice.options[index].value
        
        //(获取value) 方法二:
        // 当我们要取得select的选中事件时,用 document.all['name'].value 来获取,
        // 其中name是select的名称
              var color = document.all['col'].value
              console.log(color);   
        
            // 改变字体颜色
              text.style.color = color
              
           }
           
</script>

Guess you like

Origin blog.csdn.net/weixin_45959965/article/details/128338661