简体   繁体   English

img标签显示文件夹中的img但背景图片不显示?

[英]img tag displaying img from folder but background-image not?

I'm using the below code to pull through user uploads into a portfolio. 我正在使用以下代码将用户上传的内容拉入投资组合。 It's working great however one image (out of a list of many) is showing blank - yet displays on the next page, using the same path, but within a conventional <img /> tag. 效果很好,但是一个图像(从很多列表中)显示为空白-却在下一页上使用相同的路径显示,但在常规<img />标签内。

<?php
    $files= glob('./uploads/users/'. $item->user_id .'/'.$item->id.'/public_large/*');
    $count = 0;
    $user_avatar = '/themes/users/assets/img/noartwork.jpg'; 

    foreach ($files as $file) {
        $count++;
        if ($count > 0 && is_file($file)) { 
            $user_avatar = $file;
        } 
    }
?>   
<div class="user-img" style="background-image:url('<?php echo site_url($user_avatar); ?>');"></div>

When I inspect element on the image that's not displaying, if I change the single quotes background-image:url('<?php echo site_url($user_avatar); ?>'); 当我检查未显示的图像上的元素时,如果我更改了单引号background-image:url('<?php echo site_url($user_avatar); ?>'); to double background-image:url("<?php echo site_url($user_avatar); ?>"); 翻倍background-image:url("<?php echo site_url($user_avatar); ?>"); it pulls through, but this is not the case if I make this change in the actual code. 它可以实现,但是如果我在实际代码中进行此更改,则不是这种情况。

Any help would be great. 任何帮助都会很棒。

Thanks 谢谢

have you tried removing single quotes? 您是否尝试删除单引号? like this : 像这样 :

 background-image:url(<?php echo site_url($user_avatar); ?>);

I found the fix for this. 我找到了解决办法。 It was to do with the users file name containing a special character that I wasn't checking for eg my-user's-image.jpg breaks the code as the character needs to be escaped my-user\\'s-image.jpg . 这与用户文件名包含一个我没有检查的特殊字符有关,例如, my-user's-image.jpg破坏了代码,因为该字符需要转义my-user\\'s-image.jpg

I amended the foreach to run a check as below and this is now working. 我修改了foreach来进行如下检查,现在可以正常工作了。

foreach ($files as $file) {
    $count++;
    if ($count > 0 && is_file($file)) { 
        $user_avatar = str_replace("'", "\'", $file);
    } 
}

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM