2016-06-26 9 views
1

こんにちは私はこのすべての初心者で、読み込み時にdivを表示するドロップダウンメニューで本当に苦労しますが、divを非表示にしてドロップダウンから選択したものを別のものに置き換えます。私はこの権利を得るために何時間も費やして、いくつかのオプションを見てきました。私が一番近いのはan earlier question on thisです。私はis hereに定住しました。Div選択の非表示

「選択...」したくないので少し修正しました。

スクリプトはCSSと同じです。

<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

はwindow.onload = functiを置くようにしてくださいon(){スクリプトの冒頭で –

答えて

0

あなたは、本体の終わりに、あなたのコードを追加したり、あなたがwindow.onloadイベントを使用することができますここで私は適応してきたHTMLです:

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>

+0

クイックレスポンスありがとう...どうすれば、Load 1に表示するContent 1 divを取得し、オプション2が選択されている場合はContent 2に、Option 3が選択されている場合はContent 3に置き換えられます等?私がほぼそこにいるように聞こえますが、本当にまっすぐなものがありません:) –

+0

@StuartThompsonあなたは私の更新スニペットのような変更イベントを引き起こすかもしれません。 – gaetanoM

+0

現時点ではコンテンツ1に負荷がかかっていません。 Thx again –

関連する問題