SVG Interativo
Criar SVGs interativos: eventos, JavaScript e formulários em SVG
O que você vai aprender
- Adicionar interatividade a SVG com eventos JavaScript (click, hover)
- Usar CSS :hover e :focus para efeitos interativos sem JavaScript
- Criar tooltips e popups dentro de SVG com elementos
e CSS - Entender limitações de segurança: SVG inline vs.
vs.
SVG Interativo🔗
Eventos SVG🔗
onmouseover/onmouseout🔗
<circle cx="50" cy="50" r="40" fill="blue"
onmouseover="this.setAttribute('fill', 'red')"
onmouseout="this.setAttribute('fill', 'blue')"/>onclick🔗
<rect x="10" y="10" width="80" height="80"
onclick="alert('Clicado!')"/>JavaScript em SVG🔗
Exemplo: Toggle Cor🔗
<svg>
<script type="text/javascript">
<![CDATA[
function toggleColor(el) {
var current = el.getAttribute('fill');
el.setAttribute('fill', current == 'blue' ? 'red' : 'blue');
}
]]>
</script>
<circle cx="50" cy="50" r="40" fill="blue" onclick="toggleColor(this)"/>
</svg>Animação com requestAnimationFrame🔗
<svg>
<script type="text/javascript">
<![CDATA[
var angle = 0;
function animate() {
var circle = document.getElementById('rotating');
angle += 2;
circle.setAttribute('transform', 'rotate(' + angle + ' 50 50)');
requestAnimationFrame(animate);
}
animate();
]]>
</script>
<circle id="rotating" cx="50" cy="50" r="30" fill="blue"/>
</svg>Formulários em SVG🔗
Checkbox🔗
<svg>
<rect x="5" y="5" width="20" height="20" fill="white" stroke="black"
onclick="this.setAttribute('fill', this.getAttribute('fill')=='blue'?'white':'blue')"/>
</svg>Slider🔗
<svg>
<rect x="10" y="10" width="100" height="10" fill="gray"/>
<circle cx="50" cy="15" r="8" fill="blue" id="slider"
ondrag="updateSlider(event)"/>
</svg>Boas Práticas🔗
- Mantenha JavaScript mínimo
- Use CSS para animações quando possível
- Teste em múltiplos navegadores
- SVGs interativos funcionam melhor inline em HTML
Para SVGs externos, eventos JavaScript podem ser bloqueados por políticas de segurança. Teste sempre em contexto real.
Você aprendeu
- SVG inline aceita eventos JavaScript e CSS interativo diretamente
- CSS :hover/:focus produz interatividade sem JavaScript para efeitos visuais
- SVG embutido via
não executa scripts
- usar