嗨那里_我是所有这一切的新手,并且真的在下拉菜单中苦苦挣扎,显示加载时的div但是然后隐藏div并从下拉列表中替换另一个选择。我花了好几个小时试图做到这一点并查看了许多选项。我得到的最接近的是对an earlier question on this的回复。我已经确定了is here。
我稍微调整了一下,因为不想“选择......”。
脚本和CSS一样保持不变。这是我改编的HTML:
<select id="target">
<option value="content_1">Option 1</option>
<option value="content_2">Option 2</option>
<option value="content_3">Option 3</option>
</select>
<div id="content_1" class="inv" style="width:250px; margin-left:-10px; height:420px">Content 1</div>
<div id="content_2" class="inv" style="width:250px; margin-left:-10px; height:420px">Content 2</div>
<div id="content_3" class="inv" style="width:250px; margin-left:-10px; height:420px">Content 3</div>
以防万一这是脚本:
<script>
document
.getElementById('target')
.addEventListener('change', function() {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null) {
target.className = 'vis';
}
});
</script>
答案 0 :(得分:0)
您可以在正文末尾添加代码,也可以使用window.onload事件:
window.onload = function() {
document
.getElementById('target')
.addEventListener('change', function() {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null) {
target.className = 'vis';
}
});
// send change event to element to select the first div...
var event = new Event('change');
document.getElementById('target').dispatchEvent(event);
}
.inv {
display: none;
}
<select id="target">
<option value="content_1">Option 1</option>
<option value="content_2">Option 2</option>
<option value="content_3">Option 3</option>
</select>
<div id="content_1" class="inv" style="width:250px; margin-left:-10px; height:420px">Content 1</div>
<div id="content_2" class="inv" style="width:250px; margin-left:-10px; height:420px">Content 2</div>
<div id="content_3" class="inv" style="width:250px; margin-left:-10px; height:420px">Content 3</div>