我正在尝试使用CSS和Javascript在select标签上做一些自定义箭头动画。
当用户单击选择标签时,我将.arrow__up
类添加到选择标签的parentNode.parentNode
中。如果选择标记.arrow__up
已经包含parentNode.parentNode
类,并且单击文档时,我将删除.arrow__up
类。
我看到的主要问题是在某些设备中,如果我单击页面document.addEventListener('click',function(){})
上的任意位置,select标记处于聚焦状态时,则不起作用。我需要在单击窗口时删除该类,因为当用户在专注于选择标记后单击窗口时,我需要向下箭头。
// selectin all select tags
var selectMenuItems = document.querySelectorAll('.sort select');
selectMenuItems.forEach(curItem => {
curItem.addEventListener('click', function(e) {
// arrow up
if(this.parentNode.parentNode.classList.contains('arrow__up')) {
this.parentNode.parentNode.classList.remove('arrow__up');
}
// arrow down if it is already up
else{
selectMenuItems.forEach(hasMenuShowItem => {hasMenuShowItem.parentNode.parentNode.classList.remove('arrow__up')});
this.parentNode.parentNode.classList.add('arrow__up');
}
});
});
// arrow down when click on window
document.addEventListener('click', function(e) { // this event is not triggering if any select tag is open on the page
console.log(e.target);
if(e.target.tagName === 'SELECT') return; // if user clicks on select tag
selectMenuItems.forEach(hasMenuShowItem => {hasMenuShowItem.parentNode.parentNode.classList.remove('arrow__up')});
});
select {
-moz-appearance: none;
/* Firefox */
-webkit-appearance: none;
/* Safari and Chrome */
appearance: none;
}
.sort {
display: inline-block;
}
.sort select {
width: 140px;
background: transparent;
padding: 16px;
}
.sort__arrow {
position: absolute;
right: 20px;
height: 8px;
width: 8px;
border: 2px solid #2f2f2f;
border-top-color: transparent;
border-right-color: transparent;
-webkit-transform: translateY(-25%) rotate(-45deg);
-moz-transform: translateY(-25%) rotate(-45deg);
-ms-transform: translateY(-25%) rotate(-45deg);
-o-transform: translateY(-25%) rotate(-45deg);
transform: translateY(-25%) rotate(-45deg);
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
-ms-transition: all 0.3s;
-o-transition: all 0.3s;
transition: all 0.3s;
}
.sort__year, .sort__month {
position: relative;
background: #fff;
display: flex;
align-items: center;
}
.sort__year, .sort__month {
position: relative;
background: #fff;
display: flex;
align-items: center;
}
.arrow__up .sort__arrow {
-webkit-transform: translateY(0) rotate(135deg);
-moz-transform: translateY(0) rotate(135deg);
-ms-transform: translateY(0) rotate(135deg);
-o-transform: translateY(0) rotate(135deg);
transform: translateY(0) rotate(135deg);
}
<div class="sort">
<div class="sort__month ">
<div class="sort__arrow"></div>
<label>
<select class="sort-select">
<option class="" value="">All</option>
<option >January</option>
<option >February</option>
<option >March</option>
<option >April</option>
</select>
</label>
</div>
</div>
<div class="sort">
<div class="sort__year sort-by">
<div class="sort__arrow"></div>
<label>
<select class="sort-select">
<option class="" value="">All</option>
<option >2018</option>
</select>
</label>
</div>
</div>
并相信我在Mac OS和其他某些设备上遇到了问题,并且在Windows上运行正常。
如何在所有设备上使用此功能?