开发者

Just a part of .attr()

I have an img html block <img src="folder1/folder2/folder3/logo1.png"> positioned inside a big div like this

<div id="editorial">
   <div id="img_editorial"><img src="folder1/folder2/folder3/logo1.png" /></div>
</div>

When user hovers the <div id="editorial"> (mouseover) i want to read the attribute of <img> which is folder1/folder2/folder3/logo1.png extract the logo1.png from this and add on_ to the logo ( on_logo1.png ) and then output it with jquery .html() function to overwritte <div id="img_editorial">

On mouseout i want to return to logo1.png ... because i have multiple bac开发者_开发问答kground changes in that parent div ... so the basic functionality is to grayout a logo when mouse is over a big div (also div`s background changes ... etc) ...

So .. how can i read the <img> attribute and then extract logo1.png and not the whole folder1/folder2/folder3/logo1.png ...


You can read the attribute like this:

var img_src = $('#img_editorial img').attr('src');

This will give you:

folder1/folder2/folder3/logo1.png

Than you can split it with:

var split_img_src = img_src.split('/');

This will give you an array, something like:

split_img_src[0] = folder1;
split_img_src[1] = folder2;
split_img_src[2] = folder3;
split_img_src[3] = logo1.png;

so the last value in the array should always be the name of the file - no matter how long the directory tree is.

So you now have the file name, you can append what ever you want to it and do what ever you need.

Good luck.


Here! just a nice solution:

$('#img_editorial img').hover(function(){

   imgSrc = $(this).attr('src');
   var imgSplit = imgSrc.split('/');
   var imgName = imgSplit[3];

   $(this).attr('src', imgSrc.replace(imgName, 'on_'+imgName) );

},function(){

    $(this).attr('src', imgSrc);

});

If you want, open Firebug and play with this DEMO


The following should do what you want. It just stores the original image using the jQuery .data() API and puts it back when on .mouseleave() of the <div>.

$('div#editorial').mouseenter(function() {
    var originalSrc = $('img', this).prop('src');
    $(this).data('originalSrc', originalSrc);
    var pathComponents = originalSrc.split('/');
    var logo = pathComponents.pop();
    pathComponents.push('on_' + logo);  
    $('img', this).prop('src', pathComponents.join('/'));
}).mouseleave(function() {
    $('img', this).prop('src', $(this).data('originalSrc'));
});

The demo sort of works but I have no _on image so it just 404s. I hope you get the idea :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜