douyueju2912 2012-02-11 19:01
浏览 28
已采纳

调整文本中<img>标签的宽度/高度

I have a chunk of HTML with has images in it. These image tags have a defined width and height:

<img width="300" height="80" src="image.jpg" />

I would like to go through this HTML and replace the width and heights of the images width a % value instead based off 100%=600 and remove the height attribute all together. So, for example, if an image has a defined width of of 300, the width would be replaced with 50%:

<img width="50%" src="image.jpg" />

I'm pretty rubbish with REGEX, but I image its pretty much going to be the answer. So please help.

In case anyone is wondering, this is needed to format blog post HTML into something that will display friendly on a fluid mobile version of the blog. At the moment, creating actual resized copies of the images is not a viable solution.

I have jquery, jquery mobile available as well if there is a javascript approach to this problem.

  • 写回答

3条回答 默认 最新

  • duanshaiduhao2471 2012-02-11 19:09
    关注

    Try this simple code:

    $('img').removeAttr('height').attr('width', function() {
        return Math.round((this.width * 100)/600) + '%'; 
    });
    

    Or another variant:

    $('img').css('width', function() {
        return Math.round((this.width * 100)/600) + '%'; 
    }).removeAttr('width height');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办