너와 나의 프로그래밍

JavaScript - IE에서 Selectbox의 Option Text의 Color가 변하지 않을 때 본문

Front-End/JavaScript

JavaScript - IE에서 Selectbox의 Option Text의 Color가 변하지 않을 때

Whatever App's 2019. 4. 26. 11:21

 

SelectBox의 Option의 Text color를 바꾸는 동작을 구현하는 중 IE에서만 Text의 Color가 정상적으로 변경되지 않는 문제가 발생하였다.

 

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<script>
window.onload = function(){
var selectbox = document.getElementsByTagName('select')[0];
var options = selectbox.querySelectorAll('option');

document.getElementById('change').addEventListener('click', function(){
for(var i = 0; i < options.length; i++) {
options[i].style.color = 'blue';
}
});

document.getElementById('cancel').addEventListener('click', function(){
for(var i = 0; i < options.length; i++) {
options[i].style.color = 'black';
selectbox.selectedIndex = '-1';
}
})
}
</script>
<body>
<select multiple>
<option>test1</option>
<option>test2</option>
</select>

<button id = "change">Change</button>
<button id = "cancel">Cancel</button>
</body>
</html>

 

위 소스 코드를 보자면...

 

처음 'change' 버튼을 눌렀을 때 option의 Text 색상이 Blue로 바뀌고 다시 'cancel' 버튼을 눌러 Black 색상으로 돌아오는 코드다.

 

타 브라우저는 정상 동작하지만 IE에서만 SelectBox의 focus를 줘야 색상이 바뀌는 아이러니한 현상이 발생하였다...  

 
한 2틀? 3일 정도 찾아봐도, Stackoverflow에 도움을 요청해보고 각종 웹 개발 커뮤니티에도 도움을 요청해 봤지만 해결이 안되는 도중.
 
우연히 selectedIndex속성을 보고 혹시?나 하는 마음에 적용해 봤지만 아주 정상적으로 동작했다.
 
대신 '-1'를 쓴 이유는 기본적으로 0으로 주는 경우가 많지만 나는 딱히 option을 선택하지 않을거라 단지 Selectbox에만 focus를 주도록 하였다.
 
 
 
 
 
 
 
 
 

(IE는 이 세상에서 꼭 사라졌으면 좋겠다.)

 

반응형