如何悬停在SVG矩形上?

35

这段SVG代码在多个浏览器(FF 8、Safari 5.1.2、Chrome 16,均在Mac上测试)中存在问题:当鼠标移动到矩形条上时,浏览器无法正确侦测到每个on-mouse-over/out事件,有时它有效,有时则无效。但所有的浏览器行为都一致,因此可能是SVG代码的问题。使用onmouseoveronmouseout会得到同样的结果 - 不工作。

在SVG rect元素上实现悬停的正确方法是什么?

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"  width="800" height="600" version="1.1" style="display:inline">

<style type="text/css">
.bar {
    fill: none;
}
.bar:hover { 
    fill: red;
}
</style>
  <g>
   <rect class="bar" x="220" y="80" width="20" height="180" stroke="black" stroke-width="1" />
  </g>
</svg>
5个回答

68

发生的情况是鼠标事件未被检测到,因为填充颜色是“none”,只需添加:

.bar {
    fill: none;
    pointer-events: all;
}

那么它就能完美运行。


6

fill: none; pointer-event: all;在大多数现代浏览器中都能正常工作,但是IE9和IE10不支持pointer-events。此外,您还可以设置pointer-events:fill,这个fill值只适用于SVG,意味着fillvisibility的值不会影响指针事件处理。

如果不支持pointer-events(您可以使用Modernizr来检测浏览器功能),那么IE9和IE10的解决方法是将CSS设置为fill:transparent

$("#rect").mouseenter(function() {
  $(this).css("fill", "teal")
}).mouseout(function(){
  $(this).css("fill","transparent")
})
#rect {
  fill: transparent;
  stroke: blue;
  stroke-width: 1px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

<svg width=300 height=300>
  <rect id="rect" x=0 y=0 width=100 height=100></rect>
</svg>


4
.bar:hover { 
    fill: red !important;
}

2
说实话,我认为这不会改变任何事情。.bar:hover.bar更具体,因此样式仍然会接管。 - tomekwi

1
尝试给它一个不透明的填充。

另外,<style> 需要放在 <svg> 的外面。


你的答案是正确的,但是在<svg>中使用<style>是可以的:http://www.w3.org/TR/SVG/styling.html#StyleElement - Peter Collingridge

-3

尝试通过jQuery实现:

$(".bar").attr("disable","True");
$(".bar").css("background-color","Red");

$(".bar").mouseenter(function() {   
    $(this).attr("disable","False");  
}); 

$(".bar").mouseleave(function() {   
    $(this).attr("disable","True");  
});

或者另外一种选择:

$(".bar").hide();
$(".bar").css("background-color","Red");

$(".bar").mouseenter(function() {   
    $(this).show();  
}); 

$(".bar").mouseleave(function() {   
    $(this).hide(); 
}); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接