이미지 hover시 색 변화 문제
조회수 707회
각각 색이 다른 3가지 이미지가 있고 해당 이미지에 마우스를 호버시키면 일정 값으로 바뀌었다가
마우스 리브시에 다시 원래색으로 돌아가는 코드를 짜려합니다.
var strong = "#01152c";
var strong_hover = "#001121";
var normal = "#041c3a" ;
var normal_hover = "#032549";
var weak = "#082750";
var weak_hover ="#0b345e";
$(".area").hover(function(){
if(this.attributes.fill.value == strong) {
this.style.fill = strong_hover;
} else if (this.attributes.fill.value == normal) {
this.style.fill = normal_hover;
} else if (this.attributes.fill.value == weak) {
this.style.fill = weak_hover;
}
}, function(){
if(this.attributes.fill.value == strong_hover){
this.style.fill = strong;
} else if (this.attributes.fill.value == normal_hover){
this.style.fill = normal;
} else if (this.attributes.fill.value == weak_hover){
this.style.fill = weak;
}
});
이런식으로 코드를 짜봤는데 호버시에 원하는색으로까지는 바뀌는데 본래의 색으로 돌아오지 않습니다.
어떤 문제가 있을까요?
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
스타일 속성값은 set 한 값 그대로 get 할수 있다고 장담할 수 없습니다. 이는 CSS 스타일 속성값들은 내부적으로 computed된 값을 리턴하기 때문인데요.
이렇기 때문에 대입한 값 그대로 비교를 하면 당연히 거짓이 뜹니다.
보통 위와 같은 스타일 지정은 클래스로 하게 되며, 미리 CSS에 선언해 둔 클래스가 존재하는지 유무로 스타일이 적용되었는지를 판단하는게 더 일반적입니다.
.strong { fill: "#01152c"; } .strong_hover { fill: "#001121"; }
$(".area").hover(function(){ if($(this).hasClass('strong')) { $(this).addClass('strong_hover'); } // ... }, function(){ if($(this).hasClass('strong_hover')){ $(this).removeClass('strong_hover'); } // ... });
참고:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
댓글 입력