gpt4 book ai didi

javascript - <script> 元素在 SVG 文件和 HTML 文件中起作用吗?

转载 作者:搜寻专家 更新时间:2023-10-31 22:13:18 25 4
gpt4 key购买 nike

我想创建一个 SVG 文件,它自己有一个由 Javascript 控制的小动画。假设我必须使用 Javascript,而不是 the fancy-pants SVG animation tools .那很好用;一个黑色圆圈在我窗口的左上角移动:

<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="400px" height="400px"
>
<circle id="c" cx="50px" cy="50px" r="20px" />
<script>
var c = document.getElementById('c');
function f() {
c.setAttribute('cx', 50 + 30 * Math.random());
c.setAttribute('cy', 50 + 30 * Math.random());
}
setInterval(f, 1000);
</script>
</svg>

现在,我想将该 SVG 添加到一些网页中。让我们试试:

<html>
<head>
<title>Test a scripted SVG in an &lt;img&gt; tag
</head>

<body>
<img src="test.svg" />
</body>
</html>

结果是一个不会四处移动的黑色圆圈。

我做错了什么?哪里说我不能这样做?

最佳答案

<script>元素在 SVG 文件中有效,但当 SVG 文件显示为图像时无效,无论是通过 <img>元素或作为 CSS 背景图像。如果您希望脚本正常工作,请替换 <img><iframe><object>元素。

基本上,SVG 在图像上下文中使用时会模拟光栅图像。光栅图像不可编写脚本,因此以这种方式使用 SVG 时也不可编写脚本。

关于javascript - &lt;script&gt; 元素在 SVG 文件和 HTML 文件中起作用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23818698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com