gpt4 book ai didi

javascript - getElementByID 可以深入到 SVG 文档中吗?

转载 作者:行者123 更新时间:2023-11-28 09:07:25 24 4
gpt4 key购买 nike

我正在尝试通过操作 SVG 文档来赚取一些 JavaScript 代码。我有以下代码:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="24" width="400" id="tmcBarLoading">
<rect id="outerrect" width="400" height="24" x="0" y="0" style="stroke-width:2px;stroke:grey;fill:none;"/>
<rect id="innerrect" x="2" y ="2" width="0" height="20" style="stroke-width:0px;" fill="blue">
<animate attributeName="width" attributeType="XML" begin="0s" dur="2s" fill="freeze" from="0" to="396"/>
</rect>
</svg>

并尝试在单击 SVG 文档中的元素时设置一个简单的警报:

    $(document).ready(function () {
'use strict';

var img = document.getElementById("spikeroad");
console.log(img);
var delta = img.getElementById("outerrect");
delta.addEventListener("click", function() {
alert('Delta clicked');
}, false);
});

该脚本可以很好地找到该图像,但在单击该图像时无法将警报附加到该图像。我希望能够使用 JavaScript 将动画事件动态附加到对象,但我需要首先弄清楚如何识别它们。

这一切都在这个 html 中:

<html>
<head>
<title>My Title</title>
<meta charset="utf-8">
<script defer="defer" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script defer="defer" src="controls.js" type="text/javascript"></script>
</head>
<body>
<img id="spikeroad" src="map.svg" alt="loadbarspike"/>
</body>
</html>

最佳答案

我认为你应该将你的javascript放入svg文档中。img.getElementById 也不是一个函数。 getElementById 仅适用于文档。

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="24" width="400" id="tmcBarLoading">

<script>
window.onload = function() {
var delta = document.getElementById("outerrect");
delta.addEventListener("click", function() {
alert('Delta clicked');
}, false);
};
</script>
<rect id="outerrect" width="400" height="24" x="0" y="0" style="stroke-width:2px;stroke:grey;fill:none;"/>
<rect id="innerrect" x="2" y ="2" width="0" height="20" style="stroke-width:0px;" fill="blue">
<animate attributeName="width" attributeType="XML" begin="0s" dur="2s" fill="freeze" from="0" to="396"/>
</rect>

关于javascript - getElementByID 可以深入到 SVG 文档中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16830653/

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