我想在网站加载时显示一个div内容(.option-1)。
document.getElementById('target').addEventListener('change', function () {
let divs = document.querySelectorAll('.initial, .vis'); // grab all divs that have the class "initial" or "vis"
for (let i = 0; i < divs.length; i++) {
// loop over all divs
let div = divs[i];
if (div.classList.contains(this.value)) {
// the div's class list contains the value of the select box, e.g. "option-1" or "option-2"
div.classList.remove('initial');
div.classList.add('vis'); // make the div visible
} else {
div.classList.add('initial');
div.classList.remove('vis'); // otherwise make the divs invisible
}
}
});
<div class="header">
<select name="dropdown" id="target">
<option value="option-1">option1</option>
<option value="option-2">option2</option>
</select>
</div>
<div class="temps">
<div class="initial option-1">Temp 1</div>
<div class="initial option-2">Temp 2</div>
</div>
<div class="forms">
<div class="initial option-1">Form 1</div>
<div class="initial option-2">Form 2</div>
</div>
.initial显示无;
.initial {
display: none;
}
发布于 2021-07-08 03:20:05
如果希望下拉列表中的第一个选项在load上运行逻辑,请添加一个具有DispatchEvent的load事件侦听器,该侦听器将模拟下拉列表中的更改。
window.addEventListener('load', function() {
let event = new Event('change');
document.getElementById('target').dispatchEvent(event);
});https://stackoverflow.com/questions/68287600
复制相似问题