You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Annotorious.js,如何在JavaScript数组中获取Target对象并添加类?

使用Annotorious.js展示所有注释文本内容

核心实现思路

从你提供的注释数组结构来看,每个注释对象的body数组中,type为TextualBody的项里的value字段就是需要的注释文本内容。只需遍历数组提取这些文本,再渲染到页面即可。

代码实现

  1. 先在页面中添加一个用于展示注释的容器:
<div id="annotations-display"></div>
  1. 提取并渲染注释文本的JavaScript代码:
// 获取所有注释
const annotations = anno.getAnnotations();
// 获取页面上的展示容器
const displayContainer = document.getElementById('annotations-display');

// 遍历每个注释
annotations.forEach(annotation => {
  // 遍历注释的body内容(兼容单注释多文本的场景)
  annotation.body.forEach(bodyItem => {
    // 筛选出文本类型的注释内容
    if (bodyItem.type === 'TextualBody' && bodyItem.value) {
      // 创建展示文本的元素
      const textElement = document.createElement('div');
      // 添加自定义CSS类用于样式控制
      textElement.classList.add('annotation-item');
      // 设置文本内容
      textElement.textContent = bodyItem.value;
      // 将元素添加到容器中
      displayContainer.appendChild(textElement);

      // 如果需要把文本放入文本框,替换为以下代码
      // const textarea = document.createElement('textarea');
      // textarea.className = 'annotation-textarea';
      // textarea.value = bodyItem.value;
      // displayContainer.appendChild(textarea);
    }
  });
});
  1. 自定义样式示例(可按需调整):
.annotation-item {
  margin: 10px 0;
  padding: 12px;
  background-color: #f0f8ff;
  border-radius: 4px;
  border-left: 4px solid #1e90ff;
  line-height: 1.5;
}

/* 文本框样式(如果使用的话) */
.annotation-textarea {
  width: 100%;
  height: 80px;
  margin: 10px 0;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
}

关键说明

  • 确保页面中存在annotations-display容器元素,否则代码无法找到渲染目标
  • 注释的body数组可能包含多种类型内容,需通过type: 'TextualBody'筛选文本注释
  • 可根据需求选择渲染为普通文本块或文本框,替换对应的DOM创建代码即可

内容的提问来源于stack exchange,提问作者Ekin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 02:12:09