📅  最后修改于: 2023-12-03 15:05:25.217000             🧑  作者: Mango
SVG <script>
element allows you to embed scripts in SVG content. This script can contain any JavaScript code within its script body, and it can be used to manipulate or modify SVG images, add interactivity to SVG content, create animations, and much more.
<svg>
<script type="text/javascript">
// JavaScript code
</script>
</svg>
type
: specifies the MIME type of the script. It must be set to "text/javascript"
.href
: specifies the URL of the script file to be included.SVG script element can be directly included in SVG markup by enclosing the JavaScript code within the <script>
tag. For example, the following code checks if the user has clicked on the SVG element:
<svg width="300" height="200">
<script type="text/javascript">
document.addEventListener("click", function(event) {
if (event.target.nodeName === "svg") {
console.log("You clicked on the SVG element.");
}
});
</script>
</svg>
SVG script element can also be used to load external JavaScript files. For example, the following code loads an external script file and uses its functions to create a simple animation:
<svg width="300" height="200">
<script type="text/javascript" href="animation.js"></script>
<rect x="0" y="0" width="50" height="50" fill="red" id="rect"/>
</svg>
// animation.js
var rect = document.getElementById("rect");
function animate() {
var x = parseInt(rect.getAttribute("x"));
x = (x + 1) % 200;
rect.setAttribute("x", x);
}
setInterval(animate, 5);
SVG script element has some limitations that you should be aware of:
"image/svg+xml"
) to work properly.