javascript - 更改复杂 SVG 中的文本

标签 javascript html dom svg

我有一个翻页日历的小型 SVG 插图。我添加了一个文本字段,其中当前显示“数字”。我试图显示自特定日期以来已经过去了多少天,但由于每天都会增加一天,我希望有一个事件脚本来更新我网站上的数字。插图是在 Adob​​e Draw 上制作的,因此笔画相当冗长且令人困惑,因此为了清晰起见,我删除了 SVG 的所有插图部分 - SVG 标签内只有文本字段。

我认为我错过了关于如何更改文本字段的内部文本的关键点。在我在 MDN Web 文档上找到的示例中,您可以使用 DOM 更改 SVG 内的属性,但我没有运气。我已经尝试过:

   document.getQuery(".calendar").innerText = diffDays; 
   document.getElementsByClass("calendar").innerText = diffDays;
   document.getElementById("journaled").innerText = diffDays;

<svg id="test" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 99 75.5">

<script type="text/javascript">
  const start = new Date('5/23/2013');
  const today = new Date();
  const diffTime = Math.abs(today - start);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

  document.getQuery(".calendar").textContent = "is anything working?";
  document.getElementsByClassName("calendar").textContent = diffDays;
  document.getElementById("journaled").textContent = diffDays;
</script>

<defs>
  <style>
    .calendar {
      font-size: 12px;
      font-family: Georgia;
    }
  </style>
</defs>
<text contentEditable="true" class="calendar" id="journaled" transform="translate(20 51.63)">number</text>

</svg>

我还研究了控制台中显示的问题“Uncaught TypeError: document.getQuery is not a function”,并且我找不到任何与 SVG 相关的资源。任何帮助将不胜感激。 JSFiddle

最佳答案

我删除了 getQuerygetElementsByClassName

并提取你的JavaScript外部svg并且它可以工作......试试这个:

const start = new Date('5/23/2013');
      const today = new Date();
      const diffTime = Math.abs(today - start);
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 

      document.getElementById("journaled").textContent = diffDays;
<svg id="test" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 99 75.5">
  <defs>
    <style>
      .calendar {
        font-size: 12px;
        font-family: Georgia;
      }

    </style>
  </defs>
  <text contentEditable="true" class="calendar" id="journaled" transform="translate(20 51.63)">number</text>
</svg>

关于javascript - 更改复杂 SVG 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59806846/

相关文章:

javascript - 第一个 child 最后一个 child Dom 遍历不起作用

php - 使用 PHP DOM 添加指向元素的链接

jquery - HTML DOM 和 JQuery 哪个更高效

javascript - AngularJS:在隔离范围内获取属性定义指令的值

javascript - 文档数据库 : How to define a callback function in stored procedures when using JavaScript Language Integrated Query?

html - 如何在图像上添加多个复选框

html - 当 div 位置为 :absolute 时垂直对齐标题

javascript - 无法为.HTA页面中带有JS的元素设置新的innerHTML

javascript - 我希望点击文本框后 div 内容消失

html - 大型 HTML 表格到本地数据库