2012-07-03 59 views
0

我做导航功能,将导航默认图像更改为悬停图像。jquery .hover()导航

默认图像名称是“main.png”和悬停图片是“main_hover.png”

我知道如何从HTML src属性的jQuery的帮助下提取图像的名字,但我倒知道如何添加额外的

$(document).ready(function(){ 
    $(".nav").hover(function(){ 
     var default_button = this.src; 
     // here is part where i need help with adding "_hover" to default_image 
     $(this).attr('src', default_button) // i know i need this after image is not hovered 
    }); 
}); 

回答

0
$(document).ready(function(){ 
    $(".nav").hover(function(){ 
     var default_button = this.src.replace(".jpg","_hover.jpg"); 
     $(this).attr('src', default_button) 
    }); 
}); 
+0

我需要添加几行,但thx求助! .replace()使这个工作成为可能! :) – aainaarz

5

可能是你不应该通过jQuery做到这一点,为什么不使用CSS道:“png格式”

我到目前为止的代码文件名“主”和文件扩展名之间的字符串?

.nav { 
background: url(/path/to/main.png) 
} 

.nav:hover { 
    background: url(/path/to/main_hover.png) 
} 
+0

+1绝对这一点。没有理由使用JavaScript的东西,CSS可以处理得很好。 –

+2

我想建议把悬停和常规状态放在一个图像中,如果可能的话,在悬停时使用背景位置。 –

+1

@MatthewGrima Spriting的确是最好的方式来做到这一点 –