【发布时间】:2023-01-29 21:38:31
【问题描述】:
我在 Prestashop 商店中用于商品描述的代码有问题。关键是当我在商店中添加 html 描述时,我没有提供照片的“ALT”属性。我有自动执行此操作的脚本。
这是我添加到项目完整描述中的 html 代码:
<img class="img" src="https://static.vecteezy.com/system/resources/previews/000/547/596/original/hearts-icons-vectors-illustrations.jpg" width="200" height="300">
保存更改后,浏览器中显示的代码如下所示:
<img class="img" src="https://static.vecteezy.com/system/resources/previews/000/547/596/original/hearts-icons-vectors-illustrations.jpg" alt="hearts icons vectors illustrations" width="200" height="300"><p class="alt">hearts-icons-vectors-illustrations.jpg</p>
脚本添加的代码的第二部分用于在将鼠标悬停在照片上时显示照片的名称。
这就是问题所在。关键是脚本添加的数据与另一个脚本添加到照片“ALT”的数据相同。没有“——”和“.jpg”人物。
JS 和 CSS 文件在主题文件夹中:“自定义 CSS”和“自定义 JS”
这是我在 Prestashop 商店中使用的完整代码:
$(".img").wrap('<div class="alt-wrap"/>');
$(".img").each(function () {
$(this).after('<p class="alt">' + $(this).attr("alt") + "</p>");
});
$(document).ready(function () {
$("img").each(function () {
var $img = $(this);
var filename = $img.attr("src");
if (typeof attr == typeof undefined || attr == false) {
var altText = filename.substring(
filename.lastIndexOf("/") + 1,
filename.lastIndexOf(".")
);
altText = altText.replace("-", " ").replace(".jpg", "");
$img.attr("alt", altText);
}
});
});
.img2 {
max-width: 100%;
height: 100%;
margin: 0;
padding: 0px;
column-count: max-width;
background-color: white;
}
.img-wrap {
display: flex;
flex-wrap: wrap;
flex-direction: row;
justify-content: space-around;
}
.img {
display: block;
}
.alt-wrap {
display: block;
position: relative;
margin: 20px;
color: whitesmoke;
border: 5px solid transparent;
border-image: linear-gradient(to right, green 25%, yellow 25%, yellow 50%,red 50%, red 75%, magenta 75%) 5;
}
.alt-wrap p.alt {
position: absolute;
opacity: 0;
left: 0; right: 0; bottom: 0;
margin: 0;
padding: 15px;
font-size: 14px;
line-height: 22px;
background-color: transparent;
transition: all 10ms linear;
transition-delay: 300ms;
text-align: center;
}
.alt-wrap:hover > p.alt {
opacity: 1;
transition-delay: 0s;
text-align: center;
font-weight: 900;
color: white;
font-size: 150%;
border: 20px solid transparent;
margin-left: 1%;
margin-right: 1%;
text-shadow: 0 0 10px black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="img2"><div class="img-wrap"><img class="img" src="https://static.vecteezy.com/system/resources/previews/000/547/596/original/hearts-icons-vectors-illustrations.jpg" width="200" height="300">
如何更改/优化上述代码,使鼠标悬停后显示的照片名称不带“-”和“.jpg”符号?
悬停时它在我的网站上显示“未定义”它显示“hearts-icons-vectors-illustrations.jpg”我希望它显示时没有“-”和“.jpg”。
Prestashop 版本 1.7.7.3。
【问题讨论】:
-
在 p 中添加它时,您可以使用 text.slice(0, -4);它将从字符串中删除最后 4 个字符,在您的例子中是 .jpg
-
在分配值时,您可以使用此 str.replace(/-/g, " ").slice(0,-4);它将替换 - 登录空格并删除最后 4 个字符,这将是 .jpg
-
我到底应该把这段代码放在哪里?
标签: javascript html jquery css prestashop