javascript 如何根据下拉选择隐藏和显示内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12684677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to hide and show content based on drop down selection
提问by nasty
I want to hide and show a div based on a drop down selection. That is if I select drop down option 1, div with the id 1 should show up, and for 2 div with id 2 and so on. But I want to do this without using jQuery but with css or Javascript. Is this possible? Heres my sample drop down. Thanks guys.
我想根据下拉选择隐藏和显示一个 div。也就是说,如果我选择下拉选项 1,则应显示 id 为 1 的 div,以及 id 为 2 的 2 div,依此类推。但我想在不使用 jQuery 而是使用 css 或 Javascript 的情况下做到这一点。这可能吗?这是我的示例下拉菜单。多谢你们。
<select name="options">
<option value="1"> Loan Protection Insurance</option>
<option value="2"> GAP or Cash Assist Insurance</option>
<option value="3"> Home Insurance</option>
<option value="4"> Landlords Insurance</option>
<option value="5"> Car Insurance</option>
</select>
<div id="1">Test</div>
<div id="2">Test</div>
回答by techfoobar
Not possible with CSS alone as you need to handle the change
event of the drop down and take appropriate action.
单独使用 CSS 是不可能的,因为您需要处理change
下拉事件并采取适当的措施。
You can do it easily via pure JS:
您可以通过纯 JS 轻松完成:
document.getElementById('id-of-select').onchange = function() {
var i = 1;
var myDiv = document.getElementById(i);
while(myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById(++i);
}
document.getElementById(this.value).style.display = 'block';
};
Demo:http://jsfiddle.net/2ukyA/
演示:http : //jsfiddle.net/2ukyA/
Update:If IDs of the DIVs are like "divname1" etc..
更新:如果 DIV 的 ID 类似于“divname1”等。
document.getElementById('id-of-select').onchange = function() {
var i = 1;
var myDiv = document.getElementById("divname" + i);
while(myDiv) {
myDiv.style.display = 'none';
myDiv = document.getElementById("divname" + ++i);
}
document.getElementById(this.value).style.display = 'block';
};
回答by TehTooya
If you don't care about "selecting", making css-only drop down menus is pretty easy.
如果您不关心“选择”,那么制作仅 css 的下拉菜单非常容易。
Check out: http://www.alistapart.com/articles/horizdropdowns/
查看:http: //www.alistapart.com/articles/horizdropdowns/
You can show/hide content using the css :hover selector.
您可以使用 css :hover 选择器显示/隐藏内容。
i.e:
IE:
<ul>
<li class="menu">
group1
<div class="dropdown">dropdown content1</div>
</li>
<li class="menu">
group2
<div class="dropdown">dropdown content2</div>
</li>
<li class="menu">
group3
<div class="dropdown">dropdown content3</div>
</li>
<li class="menu">
group4
<div class="dropdown">dropdown content4</div>
</li>
<ul>
Your css then needs to be similar to:
你的 css 然后需要类似于:
.top-menu{}
.top-menu .dropdown{display:none;}
.top-menu:hover .dropdown{display:block;}