简体   繁体   English

页面加载时默认显示 div 内容 Javascript

[英]show div content as default upon page load Javascript

I want to show one div content (.option-1) when the website is loading.我想在网站加载时显示一个 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 display none; .初始显示无;

 .initial { display: none; }

If you want the first option in the dropdown to run the logic on load, add a load event listener with a DispatchEvent that will emulate a change on the dropdown.如果您希望下拉列表中的第一个选项在加载时运行逻辑,请添加一个带有 DispatchEvent 的加载事件侦听器,该侦听器将模拟下拉列表中的更改。

window.addEventListener('load', function() {
  let event = new Event('change');
  document.getElementById('target').dispatchEvent(event);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM