我有一个翻页日历的小型 SVG 插图。我添加了一个文本字段,其中当前显示“数字”。我试图显示自特定日期以来已经过去了多少天,但由于每天都会增加一天,我希望有一个事件脚本来更新我网站上的数字。插图是在 Adobe 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
最佳答案
我删除了 getQuery
和 getElementsByClassName
行
并提取你的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/