Wordpress 主题上的缩略图在 Ajax 调用后不会获得 CSS 格式



我正在创建一个基于Wordpress (Twenty Twenty One)模板主题的新主题,并且有一个使用flexbox制作的帖子网格。

在每一篇文章中,我放上循环

<figure>
<?php echo get_the_post_thumbnail(); ?>
</figure>

返回正确的图片,我得到以下代码:

<img width="640" height="435" src="http://georg.local/wp-content/uploads/2023/03/Bildschirm_foto-2023-03-09-um-12.06.11.png" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" decoding="async" loading="lazy" srcset="http://georg.local/wp-content/uploads/2023/03/Bildschirm_foto-2023-03-09-um-12.06.11.png 640w, http://georg.local/wp-content/uploads/2023/03/Bildschirm_foto-2023-03-09-um-12.06.11-300x204.png 300w" sizes="(max-width: 640px) 100vw, 640px" style="width:100%;height:67.97%;max-width:640px;">

但是只要有Ajax调用(通过过滤器或加载更多),新帖子就有以下代码:

<img width="640" height="435" src="http://georg.local/wp-content/uploads/2023/03/Bildschirm_foto-2023-03-09-um-12.06.11.png" class="attachment-post-thumbnail size-post-thumbnail wp-post-image" alt="" decoding="async" loading="lazy" srcset="http://georg.local/wp-content/uploads/2023/03/Bildschirm_foto-2023-03-09-um-12.06.11.png 640w, http://georg.local/wp-content/uploads/2023/03/Bildschirm_foto-2023-03-09-um-12.06.11-300x204.png 300w" sizes="(max-width: 640px) 100vw, 640px">

所以,唯一的区别是Ajax调用之前的帖子有这种参数:style="width:100%;height:67.97%;max-width:640px;

我猜有某种脚本在做数学运算来找到% height的值,因为这使得图片适合postdiv。

Ajax加载后的图片没有style="在他们的标签里,所以图片显示的是原始尺寸,从容器里泄漏出来。

这是因为Wordpress设置或脚本吗?我如何确保Ajax调用后的图片也自动调整大小以适合它们的容器?

谢谢!

我创建了一个函数,根据原始图片

的比例来设置高度%。

function adjustImg() {
$('.grid-item figure img').each(
function calculateAspectRatioFit(srcWidth, srcHeight) {
var srcWidth = $(this).attr('width');
var srcHeight = $(this).attr('height');
var ratio = (srcHeight / srcWidth);
var width = "100%";
var height = ratio * 100 + "%";
$(this).css({'height': height,
'width': width,
'max-width': srcWidth});
})};

,然后在Ajax成功后调用该函数。

最新更新