前提・実現したいこと
addEventListenerで要素のクリックによってclassListをaddして、windowのクリックによりそのaddされたclassListをremoveすることはできるのでしょうか?ドロップダウンメニューの開閉に関して、display: none, blockの付け外しでul#pulldownmenuをクリックするとul#pulldownindustryが展開し、閉じる時はウインドウ内のいずれかをクリックすることによって閉じるという仕様にしたいと考えているのですが、どうもうまく行きません。
該当のソースコード
Html
1<div class="bottom"> 2 <div class="searchbox1"> 3 <ul id="pulldownmenu"> 4 <li id="text">A<span class="allow">〉</span></li> 5 </ul> 6 <ul id="pulldownindustry" class="none"> 7 <li>B</li> 8 <li>B</li> 9 <li>B</li> 10 <li>B</li> 11 <li>B</li> 12 <li>B</li> 13 </ul>
css
1#pulldownmenu { 2 width: 260px; 3 height: 30px; 4 border: 1px solid #00AED9; 5 list-style: none; 6 background: white; 7} 8 9#pulldownindustry>li { 10 background: white; 11} 12 13.allow { 14 display: inline-block; 15 transform: rotate(90deg); 16 color: #00AED9; 17} 18 19 20 21.none { 22 display: none; 23 width: 300px; 24 list-style: none; 25 background: white; 26 height: 0px; 27} 28 29.selection { 30 display: block; 31 background: white; 32} 33 34 35 36.bottom div { 37 width: 315px; 38 height: 300px; 39 background: gray; 40 margin-bottom: 17px; 41} 42
JavaScript
1'use strict'; 2{ 3 const pulldownmenu = document.getElementById('pulldownmenu'); 4 const pulldownindustry = document.getElementById('pulldownindustry'); 5 6 7 pulldownmenu.addEventListener('click', () => { 8 if (pulldownindustry.classList.contains('selection')) { 9 return; 10 } 11 pulldownindustry.classList.add('selection'); 12 const text = document.getElementById('text'); 13 text.textContent = 'XXX'; 14 }); 15 16 window.addEventListener('click', () => { 17 if (pulldownindustry.classList.contains('selection')) { 18 pulldownindustry.classList.remove('selection'); 19 } else { 20 return; 21 } 22 }); 23 24} 25
試したこと
ディベロッパーツールで確認するとwindow.addEventListnerでclassList.removeを書き込んだ時点で、pulldownmenu.addEventListenerのclassList.addでselectionが追加されなくなることを確認しました。そのため条件分岐でselectionを持っているかどうかで、処理を分けようとしたのですが、それでもうまくい行きません。toggleを使ってul#pulldownmenu要素だけにイベントを仕込めばうまく行くのですが、できればメニューを閉じるのはウインドウのクリックで実現できるようにしたいです。アドバイス頂戴できますと幸いです。
補足情報(FW/ツールのバージョンなど)
アトムエディターでクローム用に開発しています。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/29 13:44