使用原始Javascript显示图像替代文本

时间:2018-08-22 10:03:31

标签: javascript

我想使用原始JavaScript 将图像的替代文本显示为带有类的段落。

示例:

<img src="image.jpg" alt="These are planets">

渲染为:

<img src="image.jpg" alt="These are planets">
<p class="photo-caption">These are planets</p>

2 个答案:

答案 0 :(得分:1)

尝试以下方法。请注意,它使用的是es6函数

const images = Array.from( document.querySelectorAll('img') );

images.forEach(image => {
  let alt = image.getAttribute('alt');
  
  if( alt )
  {
    image.insertAdjacentHTML('afterEnd', `<p class="caption">${alt}</p>`); 
  }
});
<img src="https://placeimg.com/240/280/any" alt="These are planets">
<img src="https://placeimg.com/240/280/any" alt="These are something">
<img src="https://placeimg.com/240/280/any" alt="Something else">
<img src="https://placeimg.com/240/280/any" alt="Something">

答案 1 :(得分:0)

如果这对任何人都有用,这就是我最终得到的结果,并且效果很好。如果您想有选择地向图像添加标题而不向Markdown添加其他HTML,这将非常有用:

Jekyll / Github页面降价:

![These are planets](path/to/image.jpg){: .add-caption}

在构建时它将呈现:

<img class="add-caption" src="image.jpg" alt="These are planets">

使用@SuperDJ的JS

  const images = Array.from( document.querySelectorAll('.add-caption') );
  images.forEach(image => {
    let alt = image.getAttribute('alt');
    if( alt )
    {image.insertAdjacentHTML('afterEnd', `<p class="photo-caption">${alt}</p>`);}
  });

最终输出HTML:

<img class="add-caption" src="image.jpg" alt="These are planets">
<p class="photo-caption">These are planets</p>

添加CSS:

.photo-caption {
  color: #999;
  font-size: .5rem;
  text-align:center;
}

希望对您有帮助。我在网上搜索了一个小时,找不到解决方法。