繁体   English   中英

将 CSS class 应用于所有图像下的标题(在 JavaScript 中)

[英]Apply a CSS class to captions under all images (in JavaScript)

我在我的网站上使用 Divi 主题生成器。 我在文本块中的每个图像下方都放置了标题。 标题全部为斜体。 谁能告诉我是否可以添加一些 JavaScript 来自动识别字幕行并将 CSS class 应用于它们? 如果这可以自动化就好了,因为手动将 CSS class 添加到每个字幕会非常耗时。

这是我正在使用的 HTML:

<div class="dmpro_timeline_item_description">
  <p>
    <a style="color: inherit;" href="https://path-to-image.jpg">
      <img decoding="async" loading="lazy" src="https://path-to-image.jpg" width="300" height="237" alt="" class="wp-image-2179 alignnone size-medium" srcset="https://path-to-image.jpg 300w, https://path-to-image.jpg 1024w, https://path-to-image.jpg 768w, https://path-to-image.jpg 1536w, https://path-to-image.jpg 2048w, https://path-to-image.jpg 15w, https://path-to-image.jpg 1080w, https://path-to-image.jpg 1280w, https://path-to-image.jpg 980w, https://path-to-image.jpg 480w" sizes="(max-width: 300px) 100vw, 300px">
      <br>
      <em>This is the image caption text.</em>
    </a>
  </p>
  <p>This is where further details go (outside of the caption)</p>
</div>

如果您的图像和标题始终采用以下格式:

<img>
<br>
<em>Caption</em>

然后你可以用 CSS 来做:

img + br + em {
  font-weight: bold; /* Or whichever styles you want to give to the captions */
}

如果你想给<em>标签添加一个 class 的名字,你可以用 jQuery 来实现:

$('img + br + em').addClass('class-name-to-add');

只需将此添加到您的 javascript:

document.querySelectorAll('.dmpro_timeline_item_description em').forEach(item => {
    item.classList.add('new-class');
});

你可以用这个

$(".dmpro_timeline_item_description")
.find('img[loading="lazy"]')
.next().next()
.addClass('some-class');

这将找到具有惰性属性的图像,并将 class 添加到 img 之后的第二个元素。

由于 CSS 是从右到左阅读的,因此您应该始终尽可能简洁,在这种情况下,您应该使用通用兄弟选择器。

img ~ em {
    font-style: normal;
}

在 JavaScript 中,要申请一个 class,请执行以下操作:

const captions = document.querySelectorAll('img ~ em')

for (caption of captions) {
 caption.classList.add('caption')
}

然后你可以这样设计它:

.caption {
    font-style: normal;
}

但在这一点上,我会说最好在 CSS 中完全处理这个问题。

否则,您要求浏览器最初找到所有元素(将 class 应用于它们),然后进一步处理以根据您添加的 class 设置元素样式。 这可以通过 CSS 一步完成。

暂无
暂无

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

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