1

我想通过向父容器添加一个类来更改图像路径目录或附加图像文件。

示例:如果我向父容器添加一个“大”类img,我希望它附加img文件名或更改img路径。

   src="/images/services/image.jpg" changed to src="/images/services/image-large.jpg"

   or

   src="/images/services/image.jpg" changed to src="/images/services/large/image.jpg"

   ...............................................................................



     default, no class:

        <div>
            <img src="/images/services/image.jpg" alt="" />
        </div>

     Option 1, with class:

        <div class="large-image">
            <img src="/images/services/image-large.jpg" alt="" />
        </div>


     Option 2, with class:


        <div class="large-image">
            <img src="/images/services/large/image.jpg" alt="" />
        </div>
4

2 回答 2

3

例如像这样,使用lastIndexOf

$function() {
  var img = $(".large-image > img").each(function() { // for each img found
    var src = $(this).attr("src"); // get the src
    var path = src.substring(0,src.lastIndexOf('/')); // get the path from the src 
    var fileName = src.substring(src.lastIndexOf('/')); // and filename
    var newSrc = path+"/large"+fileName; // re-assemble   
    // or change filename:
    // var newSrc = path+"/"+fileName.replace(".jpg","-large.jpg"); // re-assemble   

    $(this).attr("src",newSrc);
  });
});
于 2012-10-18T20:09:54.887 回答
2

您可以使用 jquery 更改 src、拆分它并添加您的新文件夹

<div class="large-image">
     <img src="/images/services/image.jpg" alt="" />
</div>

$('.large-image > img').each(function(){
     var msrc=$(this).attr('src');
     msrc=msrc.split('/');     //images, services, image.jpg
     var lastelem = msrc.pop();  //images, services     // lastelem: image.jpg
     msrc.push('large');     //images, services, large   // lastelem: image.jpg 
     msrc.push(lastelem);    //images, services, large, image.jpg
     msrc=msrc.join('/');  //"images/services/large/image.jpg"
     $(this).attr('src', msrc);
})
于 2012-10-18T20:11:36.367 回答