【发布时间】:2015-10-25 05:09:32
【问题描述】:
有没有办法用下面的 div 标签替换 img 标签?
原始html:
<div class="article">
<img src="/images/img-1.jpg" alt="alt for image">
</div>
替换的html:
<div class="article">
<div style="background: transparent url(/images/img-1.jpg) no-repeat;
background-position: center center; background-size: cover; width: 566px;
height: 576px;">alt for image</div>
</div>
(可选)也可以使用父 div 的宽度和高度,即在我的示例中的文章类,而不是定义固定的width: 566px; height: 576px;?
如果可能的话,我想使用str_replace 函数。
str_replace('?????', '?????', $article);
编辑:
article 类可能有多个元素,并且文章类 div 中可能还有其他元素,我需要将 img 更改为 div。
编辑2:
我的意思是我可能在文章 div 中有任何内容,只是想用 div 替换 img。
我可能有:
<div class="article">
<h1>heading</h1>
<p>paragraph</p>
<img src="/images/img-1.jpg" alt="alt for image">
</div>
或者我可能有:
<div class="article">
<h3>heading</h3>
<p><img src="/images/img-1.jpg" alt="alt for image"> some paragraph </p>
</div>
所以,我可能在 .article div 中有任何东西,我想从中将 img 替换为 div 之类的
发件人:
<img src="/images/img-1.jpg" alt="alt for image" here-may-be-another-attribute-too>
收件人:
<div style="background: transparent url(/images/img-1.jpg) no-repeat;">alt for image</div>
【问题讨论】:
-
只需使用
width: 100%和height: 100%来适应父母的大小。 -
我需要以像素为单位进行定义。
-
如果 HTML 是动态创建的,则需要 preg_replace 函数。第二个问题 - 是的。
-
@nevermind 你能用 preg_replace 给我一个答案吗?
-
jquery 如果不是强制使用 php 会更好。