javascript - 如何在 Squarespace 模板中使用 Javascript 设置 H1 标签样式
问题描述
我们的 Squarespace 网站有一个目录,其中包含来自多个品牌的产品。我试图通过使其粗体来确保品牌名称脱颖而出,但考虑到 Squarespace 的工作方式,我需要在页面中添加 Javascript 来操作 html。
在产品标题上使用 Chrome 开发工具,我可以看到 html 类名为“.ProductList h1.ProductList-title”。
我已经尝试实现以下内容,但到目前为止还没有多少运气 - 我是否走在正确的轨道上?
function changeBrandName()
{
var prodList = document.getElementsByClassName(".ProductList h1.ProductList-title");
for (i = 0, len = prodList.length; i < len; i++)
{
prodList[i].style.color = 'red';
}
}
window.onload = changeBrandName();
Squarespace 类结构:
<section class="ProductList-overlay">
<div class="ProductList-meta">
<h1 class="ProductList-title">Vifa - Pebble Grey Oslo Loudspeaker</h1><style></style>
<div class="product-price">
<span class="sqs-money-native">0.00</span>
</div>
</div>
</section>
(这是我们展示产品的页面之一https://www.manilva.co/catalogue-electronics/)。
解决方案
看看:https ://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
当使用 getElementsByClassName 时,您不需要像您所做的那样传入 CSS 选择器。您只需要传入类的实际名称。或者,将 querySelectorAll 与您最初的参数一起使用。正如 daksh 所提到的,querySelector 只会返回匹配的第一个元素
function changeBrandName()
{
var prodList = document.querySelectorAll(".ProductList h1.ProductList-title"); //returns static NodeList of all elements in DOM that match the provided classes
for (i = 0; i < prodList.length; i++)
{
prodList[i].style.color = 'red';
prodList[i].style.fontWeight = 'bold'; //W is capital
}
}
推荐阅读
- c - 使用 MPI_Gather 和 MPI_Scatter 进行数组求和
- python - python多处理返回无,不共享计数器
- javascript - 需要帮助反转此功能
- python - 如何循环遍历两个列表字典以将唯一键值附加到一个列表字典并通过共享重复值条目继续遍历另一个?
- c++ - 注册和调用 DLL 回调的正确方法是什么
- django - 用于比较值列表更新的 Django 两个?
- laravel - Laravel:如何在表单中使用 orderBy?
- ssl - 尝试使用 SSL 设置 MQ 连接
- swift - 在 Swift 中更改大标题导航栏的字体
- java - Storm UI 中未创建 Storm 拓扑