채택완료

제이쿼리 배경이미지 url변경 질문

2021-04-09 (금) 16:37:01 2,030

이미지는 css background:url();로 

box1.jpg

box1_on.jpg

box2.jpg

box2_on.jpg

이런 식으로 되어있습니다.

마우스를 올렸을 때는 _on이 붙은 배경이 보이고 

마우스를 떼면 다시 원래 배경으로 돌아가는 기능을 하고싶은데

아래와 같이 스크립트를 짰더니 substring 요 부분에서 에러가 나더라구요.. 

script.js:28 Uncaught TypeError: Cannot read property 'substring' of undefined

에러 해결 방법이나, 아니면 새로운 방법이 있을까요? 

$(".sec1_right > ul > li").each(function(){

var nowBg = $(this).find('background'); //hover bg 찾기

var urlName = nowBg.attr('url');

var newUrl = urlName.substring(0, urlName.lastIndexOf('.'));

$(this).hover(function(){

$(this).find('background').attr('url', newUrl+'_on'+/[^.]+$/.exec(urlName));

}, function(){

$(this).find('background').attr('url', newUrl+'.'+/[^.]+$/.exec(urlName));

});

});

|

답변 2개

채택된 답변
+20 포인트
Copy
$(".sec1_right > ul > li").each(function(){
    var url_img = $(this).css('background-image');         

    $(this).hover(function(){
        $(this).css('background-image', url_img.replace('.jpg', '_on.jpg'));
    }, function(){
        $(this).css('background-image', url_img.replace('_on.jpg', '.jpg'));
    });

});

※ https://www.w3schools.com/jquery/jquery_css.asp

Copy
$(this).hover(function(){

    $(this).css('background-url', newUrl+'_on'+/[^.]+$/.exec(urlName));

}, function(){

    $(this).css('background-url', newUrl+'.'+/[^.]+$/.exec(urlName));

});

find('background') 이부분이 에러인거 같네요. 

답변을 작성하려면 로그인이 필요합니다.