Images not Cropped to correct size

别来无恙 提交于 2019-12-02 09:39:33
fuyushimoya

I found that topic, and make some test,

then I find out that s200-h150-c seems weird

So I replace

image.attr({src : image.attr('src').replace(/s\B\d{2,4}/,'s' + w + '-h' + h +'-c')});

to

image.attr({src : image.attr('src').replace(/s\B\d{2,4}/,'w' + w + '-h' + h +'-c')});

With s200-h150-c become w200-h150-c, and it works. Not sure there's typo on origin post or the function changed.

var w = 200;
var h = 150;
$('.crop').find('img').each(function(n, image){
  var image = $(image);
  image.attr('src' , image.attr('src').replace(/s\B\d{2,4}/,'w' + w + '-h' + h +'-c'));
  image.attr('width',w);
  image.attr('height',h);
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Please save the croped Image for see the actual result.
<br/><br/>
1) After Crop (Result: 150px X 150px ) 
<br><br>
<div class="crop">
<img src="http://1.bp.blogspot.com/-R7XPICyjSZA/VRaUCQteV1I/AAAAAAAABLc/PSsERo55dIg/s1600/artworks-000103151765-uxzfpd-t500x500.jpg"/>
</div>
<br/><br/>
2) After Crop (Result: 150px X 150px )
<br/><br/>
<div class="crop">
<img src="http://4.bp.blogspot.com/-YTDvE4-4L0o/VIkaNloCRCI/AAAAAAAAAu0/8Q0MkvJyGZE/s1600/pc-type65756.jpg"/>
</div>
<br/>

You're using curly braces { } inside the attr method which is not allowed to use because attr doesn't accept object {} as a parameter.

So, you can change to:

image.attr({src : image.attr('src').replace(/s\B\d{2,4}/,'s' + w + '-h' + h +'-c')});

With this:

image.attr('src' , image.attr('src').replace(/s\B\d{2,4}/,'s' + w + '-h' + h +'-c'));

But better solution would be using like this:

image.attr('src' , function(i,v){
   return v.replace(/s\B\d{2,4}/,'s' + w + '-h' + h +'-c'));
});

And you can use css for setting width and height like this:

image.css({'width':w,'height':h});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!