首页 > 解决方案 > 如何根据用户在下拉列表中的选择显示特定的 HTML 元素

问题描述

我有一个由两个条形图组成的 HTML 页面。如何在默认情况下隐藏这两个图表,根据用户在下拉菜单中的选择,“选择”选项一次只显示 1 个元素?

在此处输入图像描述

HTML:

<input type="number" id="options" value="" style="display:none">
        <select id="option">
            <option>select</option>
            <option id="option-salary"> Sort by Salary </option>
            <option id="option-age"> Sort by Age </option>
        </select>
    </input>

    <div id="bar-chart">
        <div class="salary-chart chart-container ">
            <div class="names" id="salary-names"></div>
            <div class="chart" id="salary-chart"></div>            
        </div>
        <div class="age-chart chart-container ">
            <div class="names" id="age-names"></div>
            <div class="chart" id="age-chart"></div> 
        </div>
    </div>

CSS

.chart-container{
    display: flex;
    padding: 20px;
    min-height: 100%;
}

.chart{
    border: 1px black solid;
    width: 500px;
}

.salary{
    margin: 20px;
}

.age{
    margin: 20px;
}

.name{
    margin: 20px;
}

先感谢您!

标签: javascripthtmlcssdropdown

解决方案


为此,您将需要使用 Javascript,但让我们从您的 Html 标记开始: 首先- 我们必须从 select 元素周围删除输入标记,因为它不是必需的。 第二- 我们将给每个值一个特定的值(年龄选项的“年龄”和“薪水”选项的工资)

<select id="option">
  <option>select</option>
  <option id="option-salary" value="salary"> Sort by Salary </option>
  <option id="option-age" value="age"> Sort by Age</option>
</select>

一个我们给选项的值然后我们将两个图表的显示设置display : none为 Css

.chart-container {
    display: none;
}

现在我们将在 javascript 中设置事件 onchange 以卡车选项中的任何更改,然后根据所做的选择显示一个图表

将此脚本添加到您的 Javascript 文件

//get the  Elements from the Html Document
        let sortInput =   document.getElementById('option'),
            salaryCartr =  document.querySelector('.salary-chart'),
            ageCart =  document.querySelector('.age-chart');
        
        //When the sort input changes 
        sortInput.onchange = function() {
   
            let inputValue = document.getElementById('option').value;
            // check the value returned and make the desicion
            switch (inputValue) {
                case 'age':
                    salaryCartr.style.display = "none";
                    ageCart.style.display = "block";
                    break;
                case 'salary':
                    ageCart.style.display = "none";
                    salaryCartr.style.display = "block";
                    break;

                default:
                    ageCart.style.display = "none";
                    salaryCartr.style.display = "none";
                    break;
            }
        }


推荐阅读