📜  SVG<script> Element(1)

📅  最后修改于: 2023-12-03 15:05:25.217000             🧑  作者: Mango

SVG Script Element

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.

Syntax
<svg>
  <script type="text/javascript">
    // JavaScript code
  </script>
</svg>
Attributes
  • 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.
Usage

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);
Limitations

SVG script element has some limitations that you should be aware of:

  • It can only contain JavaScript code. It cannot contain any other markup or styles.
  • It cannot be used to modify or manipulate external content that is not from the same domain.
  • The SVG document must be served with the correct MIME type ("image/svg+xml") to work properly.
  • Not all browsers support SVG script element. Some browsers may block scripts for security reasons.