【问题标题】:Get img tags without width attribute and add inline CSS attribute?获取没有宽度属性的 img 标签并添加内联 CSS 属性?
【发布时间】:2019-01-05 21:00:22
【问题描述】:

我有一个从 MYSQL 数据库打印一些 HTML 内容的 php 代码。

有时那里有一些没有任何宽度的 img 标签,所以我需要找到它们并通过内联 CSS 将 width 属性添加到这些 img 标签。

它们看起来像这样:

<img class="aligncenter size-medium wp-image-31kj" src="someimage.jpg" alt="">

<img class="alignleft large-medium wp-image-3154" src="someimage.jpg" alt="">

如何找到这些 img 标签并将其添加到它们:

style="width:100%"

提前致谢。

编辑:

已经使用 jquery 进行上述操作,但不可靠:

$(".img").each(function() {  
   var imgWidth = $(this).width();
   if (imgWidth == 0){
       $(this).css('width','100%');

   }
  });

【问题讨论】:

  • 使用 javascript querySelectorAll('img').forEach() 在 foreach 中添加您的检查并应用您想要的样式。
  • @ahmad,我已经在使用 javascript,但有时会失败,而且服务器端代码比客户端更可靠。
  • 使用解析器拉取img,检查width 属性,如果不存在则添加。
  • @user3783243 解析器是否可以处理来自 MYSQL 数据库的内容?!

标签: php


【解决方案1】:

我会用简单的、不言自明的 css 代码来做到这一点

img:not([width]) {
   width:100%;
}

只定位没有width属性的img标签

【讨论】:

  • 这不会针对使用内联 CSS 仅设置了 width 的图像。
  • 这确实有效,但不是 PHP。这种方法的可靠性如何?
  • @JamesJuanjie 你问是否可以依赖css?差不多。
【解决方案2】:

使用querySelectorAll 获取所有img 属性包含class 属性的wp-image 元素并设置样式。

document.querySelectorAll("[class*=wp-image]").forEach(function(img) {
  img.style.width = "100%";
});
<img src="https://duckduckgo.com/favicon.ico" class="wp-image-foo">
<img src="https://google.com/favicon.ico" class="wp-image-bar">

如果你想选择所有没有width属性或CSS属性的图片,使用这个:

var imgs = document.getElementsByTagName("IMG");
for (var i = 0; i < imgs.length; i++) {
  var img = imgs[i];
  if (img.style.width == "" && img.attributes.width === undefined)
    img.style.width = "100%";
}
<img src="https://duckduckgo.com/favicon.ico" class="wp-image-foo">
<img src="https://google.com/favicon.ico" class="wp-image-bar">
<img width=50 src="https://stackoverflow.com/favicon.ico" class="wp-image-bar">

【讨论】:

  • @JamesJuanjie 请在我的回答中查看编辑(第二个代码 sn-p)
猜你喜欢
  • 1970-01-01
  • 2021-07-11
  • 2013-05-25
  • 1970-01-01
  • 2019-02-05
  • 1970-01-01
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
相关资源
最近更新 更多