【问题标题】:How to hover over an SVG rect?如何将鼠标悬停在 SVG 矩形上?
【发布时间】:2012-03-01 18:27:32
【问题描述】:

在这段 SVG 中(在 FF 8、Safari 5.1.2、Chrome 16 中都在 Mac 上尝试过),当将鼠标移到栏上时,没有一个浏览器能正确检测到每个 on-mouse-over/out 事件,有时它工作有时它不。但它在所有浏览器中都是一致的,所以它可能与 SVG 代码有关。使用 onmouseoveronmouseout 会得到相同的结果 - 无法正常工作。

对于 SVG rectangles 实现悬停的正确方法是什么?

<?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>

【问题讨论】:

    标签: css svg hover


    【解决方案1】:

    发生的情况是由于填充为“无”而未检测到鼠标事件,只需添加:

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

    然后它就可以正常工作了。

    【讨论】:

      【解决方案2】:

      fill: none; pointer-event: all; 应该可以在大多数现代浏览器中运行,但 IE9 和 IE10 不支持pointer-events。另外,还可以设置pointer-events: fill,这个fill的值为SVG only,即fillvisibility的值不影响指针事件处理。

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

      $("#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>

      【讨论】:

        【解决方案3】:
        .bar:hover { 
            fill: red !important;
        }
        

        【讨论】:

        • 老实说,我认为这不会改变任何事情。 .bar:hover.bar 更具体——所以样式无论如何都会接管。
        【解决方案4】:

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


        另外,&lt;style&gt; 需要超出&lt;svg&gt;

        【讨论】:

        • 你的答案是正确的,但
        【解决方案5】:

        尝试通过 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(); 
        }); 
        

        【讨论】:

          猜你喜欢
          • 2023-03-12
          • 2012-12-29
          • 2011-11-09
          • 2019-08-10
          • 1970-01-01
          • 2015-09-12
          • 1970-01-01
          • 1970-01-01
          • 2012-05-10
          相关资源
          最近更新 更多