【问题标题】:Div Display Hide on SelectionDiv 显示隐藏选择
【发布时间】:2016-06-26 17:49:47
【问题描述】:

您好 _ 我是所有这一切的新手,并且在加载时显示一个 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>

【问题讨论】:

  • 尝试把window.onload=function(){放在脚本的开头

标签: javascript jquery html css


【解决方案1】:

您可以在正文末尾添加代码,也可以使用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>

【讨论】:

  • 感谢您的快速响应... 那么如何让 Content 1 div 在加载时显示,如果选择了选项 2,则替换为 Content 2,如果选择了选项 3,则替换为 Content 3 等等?听起来我快到了,但错过了一些非常直截了当的东西:)
  • @StuartThompson 你可能会触发一个更改事件,就像我更新的 sn-p 中一样。
  • 目前内容 1 未在加载时显示。再次感谢
  • @StuartThompson 查看 sn-p:我更新了它: var event = new Event('change');document.getElementById('target').dispatchEvent(event);再见
猜你喜欢
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多