javascript - 将当前时间写入 SVG 文档

标签 javascript svg

我正在尝试使用 ECMAScript 将当前时间添加到 SVG 文件中。 以下是我的代码。不幸的是它不起作用。我该如何修复它?

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"   width="300" height="300">
<text x="0" y="15" fill="red">It is now
<script type="text/javascript">
<![CDATA[
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
document.write(month + "/" + day + "/" + year);
]]>
</script>
</text>
</svg> 

最佳答案

演示:http://jsfiddle.net/M8YXS/

<svg xmlns="http://www.w3.org/2000/svg" width="300" height="300">
  <text x="0" y="15" fill="red">It is now <tspan id="now">(time)</tspan></text>

  <!--
    This script block must either be after the element in the source code
    or else the code below must be wrapped in a callback that is invoked
    only after the DOM is created (e.g. window.onload in a browser)
  -->
  <script>
    // Create whatever string you want
    var dateString = (new Date).toDateString();

    // Set the string content of the Text Node child of the <tspan>
    document.getElementById('now').firstChild.nodeValue = dateString;
  </script>
</svg> 

关于javascript - 将当前时间写入 SVG 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10586733/

相关文章:

HTML5 SVG - 文本定位

javascript - querySelectorAll 和事件监听器

javascript - IE9中的History.pushState添加Hash标签

javascript - SyncFusion JS 图表 - 工具提示行为错误

css - 在 CSS 中混合简单的颜色

html - 为什么 svg 元素不遵守 CSS 'bottom'、 'top'、 'left'、 'right' 属性?

javascript - console.log 打印数据两次 [reactjs]

javascript - D3JS 振荡气泡

javascript - Python Selenium 网络驱动程序 : trying to call a javascript function

css - 如何使 SVG 剪辑路径在 Google Chrome 中正常工作?