一个普通的 JavaScript 方法是可能的,尽管它确实需要一个相对最新的浏览器,因为使用了document.querySelector()
:
function selectToggle(source, map) {
var opts = source.options,
index = source.selectedIndex,
id, cur;
for (var i = 0, len = opts.length; i < len; i++){
id = map[opts[i].value];
cur = document.querySelector('#' + id);
cur.style.display = i === index ? 'inline-block' : 'none';
document.querySelector('label[for="' + id + '"]').style.display = i === index ? 'inline-block' : 'none';
}
}
var el = document.getElementById('type'),
map = {
1: 'aairport',
2: 'dairport'
};
el.onchange = function () {
selectToggle(this, map);
};
JS 小提琴演示。
以上与HTML相结合:
<label for="type">Transfer Type</label>
<select name="type" id="type">`
<option value="1">Airport to Resort</option>
<option value="2">Resort to Airport</option>
</select>
<label for="aairport">Arrival Airport</label>
<select name="aairport" id="aairport">
<option value="1">X Airport</option>
<option value="2">Y Airport</option>
</select>
<label for="dairport">Departure Airport</label>
<select name="Dairport" id="dairport">
<option value="1">X Airport</option>
<option value="2">Y Airport</option>
</select>
<label for="resort">Arrival Resort</label>
<select name="resort" id="resort">
<option value="1">Hilton Paris</option>
<option value="2">Sheraton Paris</option>
</select>
和CSS:
label, select {
display: inline-block;
float: left;
box-sizing: border-box;
margin: 0 0 0.5em 0;
}
select + label {
clear: left;
}
label {
width: 8em;
margin-right: 0.5em;
text-align: right;
}
label::after {
content:': ';
}
#dairport,
label[for=dairport] {
display: none;
}
使用 jQuery(为了展示使用库的相对简单性),它被稍微简化了:
var el = document.getElementById('type'),
map = {
1: 'aairport',
2: 'dairport'
};
$('#dairport, label[for="dairport"]').hide();
$('#type').change(function(){
var that = this;
$('.toggles').toggle(function(){
var self = this,
test = map[that.selectedIndex + 1];
return (this.id && this.id == test) || (this.htmlFor && this.htmlFor == test);
});
})
JS 小提琴演示。
稍微修改 HTML 以添加类名:
<label for="type">Transfer Type</label>
<select name="type" id="type">`
<option value="1">Airport to Resort</option>
<option value="2">Resort to Airport</option>
</select>
<label for="aairport" class="toggles">Arrival Airport</label>
<select name="aairport" id="aairport" class="toggles">
<option value="1">X Airport</option>
<option value="2">Y Airport</option>
</select>
<label for="dairport" class="toggles">Departure Airport</label>
<select name="Dairport" id="dairport" class="toggles">
<option value="1">X Airport</option>
<option value="2">Y Airport</option>
</select>
<label for="resort">Arrival Resort</label>
<select name="resort" id="resort">
<option value="1">Hilton Paris</option>
<option value="2">Sheraton Paris</option>
</select>
参考: