I have a load of social buttons ( <img>
s in a <ul>
) on the right-handle side of my site.
They might have filenames such as google.png
, or twitter.png
.
I now want to change the src
on hover to google_b.png
or twitter_b.png
- and I will consistently be naming my files in this way for all of them.
My question is how can I easily change the filenames to and from the _b
(maintaining the file extension) without having to predifine the filenames?
At the moment my code looks like this:
$('#social li').hover(function() {
// hover in
// a bunch of code to animate a tooltip is here
var $img = $t.children('img'),
src = $img.attr('src');
// change the source to img_b.png
$img.attr('src', src);
},
function() {
// hover out
var $img = $(this).children('img'),
src = $img.attr('src');
// remove _b to make it img.png again
$img.attr('src', src);
});
Assuming files won't have fake extensions ( image.png.jpeg
) just split the src on .
, add _b
to second to last part and join again on .
.
src = $img.attr('src');
var temp = src.split(".");
temp[temp.length - 2] += "_b"; //change second to last element of array
src = temp.join(".");
$('#social li').hover(function() {
// hover in
// a bunch of code to animate a tooltip is here
var $img = $t.children('img'),
src = $img.attr('src').replace(".png", "_b.png");
// change the source to img_b.png
$img.attr('src', src);
},
function() {
// hover out
var $img = $(this).children('img'),
src = $img.attr('src').replace("_b.png", ".png");
// remove _b to make it img.png again
$img.attr('src', src);
});
You could use the data function in jQuery to store the info so you won't have to constantly recalculate it.
$('#social li img').each(function(){
var image = this.src.split(".");
var onImage = image[0] + "_b." + image[1];
$(this).data("onImage",onImage);
$(this).data("offImage",this.src);
}).hover(function(){
this.src = $(this).data("onImage");
},function(){
this.src = $(this).data("offImage");
});
您可以使用jquery attr()函数直接从每个图像中提取src属性,像'_b'一样在其后附加字符,然后将其悬停。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.