SVG (Scalable Vector Graphics) 是一种基于 XML 的矢量图形格式,可以在网页中直接嵌入或通过<img>
标签引用。在 SVG 文档中运行脚本可以实现动态交互效果。
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<script>
// 当SVG文档加载完成后执行
window.addEventListener('DOMContentLoaded', function() {
console.log('SVG文档已加载');
// 可以在这里操作SVG元素
});
</script>
<circle cx="50" cy="50" r="40" fill="red" id="myCircle"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<script xlink:href="external-script.js"/>
<circle cx="50" cy="50" r="40" fill="blue"/>
</svg>
在 SVG 中常用的文档加载事件有:
DOMContentLoaded
- 当初始 HTML/SVG 文档完全加载和解析后触发load
- 当整个页面(包括所有依赖资源)完全加载后触发onload
事件原因:
解决方案:
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<script type="text/javascript">
// 确保有正确的CDATA块
<![CDATA[
console.log('脚本执行');
]]>
</script>
</svg>
原因:
解决方案:
document.addEventListener('DOMContentLoaded', function() {
var circle = document.getElementById('myCircle');
circle.addEventListener('click', function() {
this.setAttribute('fill', 'green');
});
});
原因:
解决方案:
// 正确方式创建SVG元素
var newCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
newCircle.setAttribute('cx', '30');
newCircle.setAttribute('cy', '30');
newCircle.setAttribute('r', '20');
newCircle.setAttribute('fill', 'yellow');
document.querySelector('svg').appendChild(newCircle);
DOMContentLoaded
事件确保文档已解析createElementNS
和正确的命名空间通过合理使用SVG脚本,可以创建丰富、交互式的矢量图形体验,同时保持图形的清晰度和可伸缩性。
没有搜到相关的文章