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 php 将rtmp协议转hls协议,无法播放
  • ¥15 miniconda安装不了
  • ¥20 python代码编写
  • ¥20 使用MPI广播数据遇到阻塞
  • ¥15 TinyMCE如何去掉自动弹出的“链接…”工具?
  • ¥15 微信支付转账凭证,如何解决
  • ¥15 在win10下使用指纹登录时,界面上的文字最后一个字产生换行现象
  • ¥20 使用AT89C51微控制器和MAX7219驱动器来实现0到99秒的秒表计数,有开始和暂停以及复位功能,下面有仿真图,请根据仿真图来设计c语言程序
  • ¥15 51单片机 双路ad同步采样
  • ¥15 使用xdocreport 生成word