在图像顶部添加文本 IF 图像以特定名称开头 |?JS 在类中包装图像

我的服务器上有一组以特定名称开头的图像,因此:

“communityphoto_John.jpg”

“communityphoto_Mary.jpg”等

PHP是否有可能在找到以“communityphoto_”开头的图像时在图像顶部显示文本?例如:“社区提交的照片,将您的照片提交给我们的电子邮件”

我找到了一些解决方案,但它们似乎都将文本烘焙到图像上(例如创建/保存带有嵌入文本的实际图像),但我只想在图像上显示文本,因为将来它可能会改变,但我不想替换所有图像。

我提前道歉,我不能更乐于助人,我仍然在我的PHP冒险的开始,还没有到现在为止。非常感谢您的关注和建议


隔江千里
浏览 82回答 1
1回答

收到一只叮咚

我认为在这种情况下,JavaScript和一些CSS对你来说会是一个更好的选择。根据图像的加载方式,您最好的选择仍然是解析或过滤它,并添加一个类(或一些HTML)。以以下代码段为例。它查找名称中包含的所有图像,如果找到任何图像,则循环访问它们,将它们与类一起包装在 中。communityphoto_<div>.community-image然后使用一些CSS,您可以使用::after伪类来放置一些任意文本。如果需要,您也可以将此文本添加为 JavaScript 中的 a 或某些内容。另请注意,您不能只执行 take,因为标签是&nbsp;void&nbsp;元素(也称为自闭合),在任何情况下都不会获取任何内容,因此这就是为什么我将其包装在元素中并在那里应用它的原因。<span>::afterimgimgvar communityImages = document.querySelectorAll('img[src*="communityphoto_"]');if( communityImages.length > 0 ){&nbsp; communityImages.forEach(function(image){&nbsp; &nbsp; image.outerHTML = '<div class="community-image">'+ image.outerHTML +'</div>';&nbsp; });}.community-image {&nbsp; display: inline-block;&nbsp; position: relative;}.community-image:after {&nbsp; content: "Photo submitted by the community, submit yours to our email";&nbsp; position: absolute;&nbsp; top: 5px;&nbsp; left: 5px;&nbsp; background: rgba(0,0,0,.2);&nbsp; font-size: 11px;&nbsp; padding: 3px 6px;}<div>&nbsp; <img src="https://xhynk.com/placeholder/300/100/communityphoto_1/"/>&nbsp; <img src="https://xhynk.com/placeholder/300/100/communityphoto_2/"/>&nbsp; <img src="https://xhynk.com/placeholder/300/100/something/" />&nbsp; <img src="https://xhynk.com/placeholder/300/100/communityphoto_3/"/>&nbsp; <img src="https://xhynk.com/placeholder/300/100/communityphoto_4/"/>&nbsp; <img src="https://xhynk.com/placeholder/300/100/another/"/></div>
打开App,查看更多内容
随时随地看视频慕课网APP