如何添加效果,以便将鼠标悬停在 SVG 元素上使其变大

How can I add an effect so hovering over an SVG element makes it larger?

本文关键字:SVG 悬停 鼠标 元素 添加 何添加      更新时间:2023-09-26

我有一个复杂的svg文件,其中包含许多不同的元素。我想为某些元素(或元素组)添加效果,以便它们在悬停时变大。当指针离开其区域时,它们应恢复到原始大小。 有什么好方法可以做到这一点?

我可以创建大元素的隐藏副本,并在悬停时显示它们并在之后隐藏它们,但是有没有更好的方法可以做到这一点?如果有一个对此非常有帮助的库,我可以使用库。

这是一个简单的示例,它使用 D3.js 执行了您要查找的内容。 这是一个很大的图书馆,但真的值得学习。

<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body> 
<div id="viz"></div>
<script type="text/javascript">
var sampleSVG = d3.select("#viz")
    .append("svg")
    .attr("width", 100)
    .attr("height", 100);    
sampleSVG.append("circle")
    .style("stroke", "gray")
    .style("fill", "white")
    .attr("r", 14)
    .attr("cx", 50)
    .attr("cy", 50)
    .on("mouseover", function(){d3.select(this)
        .style("fill", "green")
        .transition()                      
        .duration(1000)
        .attr("r", 28);})
    .on("mouseout", function(){d3.select(this)
        .style("fill", "white")
        .transition()                      
        .duration(1000)
        .attr("r", 14);})
</script>
</body>
</html>