悬停对SVG组元素的影响

时间:2013-10-08 17:35:22

标签: html5 css3 svg

请原谅我的无知,SVG对我来说很新鲜。我试图在我的内联SVG中对一组元素进行悬停效果。每组元素都是一组紧密排列的圆圈。我可以使用css实现这种悬停效果,但显然这只有在鼠标放在圆圈上时才有效。我想要的是当鼠标在包含圆圈的整个区域上时效果,所以空格和圆圈组合在一起。

<style>
svg {
  height: 220px;
  width: 400px;
  background: grey;
}

.na circle,
.as circle {
  fill: white;
}

.na:hover circle {
  fill: blue;
}
</style>

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <g class="na">
    <circle cx="35%" cy="2.85%" r="2.8" />
    <circle cx="36.75%" cy="2.85%" r="2.8" />
    .
    .
    <circle cx="38.5%" cy="8.55%" r="2.8" />
    <circle cx="40.25%" cy="8.55%" r="2.8" />
  </g>    
</svg>

http://jsfiddle.net/c3EaX/

当鼠标移到一个组上时,看到当你在它们之间的圆圈和空格之间移动时,悬停会闪烁。

如何让鼠标覆盖整个区域以覆盖整个区域?是否有可用于此的SVG元素?

5 个答案:

答案 0 :(得分:8)

你需要放一些东西来掩盖缺失的区域。

更简单的方法是:

.na circle,
.as circle {
    fill: white;
    stroke: transparent;
    stroke-width: 4px;
}

updated fiddle

答案 1 :(得分:8)

接受的答案对我不起作用。我找到了以下解决方案:

g {
  pointer-events: bounding-box;
  opacity: 0.4;
}
g:hover {
    opacity: 1;
}

答案 2 :(得分:1)

使用模式

对于此解决方案,您可以使用基于单个圆的pattern

在这种情况下,您无需绘制很多圆圈即可填充形状。

在填充SVG图案的图形时为圆形的克隆着色时会出现困难。

但是可以通过使图案内的圆圈着色动画来解决问题。

<animate attributeName="fill" values="white;dodgerblue" begin="path1.mouseover" dur="0.1s" fill="freeze" />

<style>
#ptn1 {
fill:dodgerblue;
}
</style>
<svg id="svg1" version="1.1" xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink"
	     width="200" height="200" viewBox="0 0 100 100" >  
<defs>
<pattern id="ptn1"   
  x="0" y="0" width="5" height="5"
  patternUnits="userSpaceOnUse">
<circle cx="3" cy="3" r="2" fill="none" stroke="grey" stroke-width="0.5" >
  <animate attributeName="fill" values="white;dodgerblue" begin="path1.mouseover" dur="0.3s" fill="freeze" />
   <animate attributeName="fill" values="dodgerblue;white" begin="path1.mouseout" dur="0.3s" fill="freeze" />
 </circle>
</pattern>
</defs>		 

<path id="path1" d="m10 50 v-5h5 v-5h5 v-5h5 v-5h5 v-5h5 v5h5 v5h5 v5h5 v5h5 v5h-45 "  stroke="none" fill="url(#ptn1)" />
</svg>

答案 3 :(得分:0)

@vals和@M_Willett的答案在MacOs(High Sierra)的Firefox v60.0.2中无效。我正在使用:

g {
  pointer-events: bounding-box;
}

在Chrome中它完美无缺。也尝试了@vals的答案,这在Firefox中也不起作用。

答案 4 :(得分:0)

另一个解决方案需要一些JavaScript,以便以编程方式获取组的边界矩形。唯一的缺点是,悬停效果将应用于该矩形,而不是组的实际形状。

const group = document.getElementById('group');
const box = group.getBoundingClientRect();

document.addEventListener('mousemove', e => {
  const hover = e.clientX > box.left && e.clientX < box.right && e.clientY > box.top && e.clientY < box.bottom;
  if (hover) {
    group.classList.add('hovered');
  } else {
    group.classList.remove('hovered');
  }
});
body {
  background: gray;
}

g > circle {
  fill: white;
}

g.hovered > circle {
  fill: blue;
}
<svg>
  <g id="group">
    <circle cx="30%" cy="20%" r="5"></circle>
    <circle cx="60%" cy="20%" r="5"></circle>
    <circle cx="45%" cy="50%" r="5"></circle>
  </g>
</svg>

相关问题