【问题标题】:SVG: Color (fill) a rectangle by hovering another rectangleSVG:通过悬停另一个矩形来为矩形着色(填充)
【发布时间】:2014-01-11 13:42:34
【问题描述】:

我需要你的帮助!

我希望能够将 SVG 图形的左侧部分(浅灰色部分)悬停。悬停时,我希望将 id="margin-bottom" 的矩形填充为红色。

链接到我的问题:http://cssdeck.com/labs/sjhr6oat

为什么我不能这样做?不可能那么难。谢谢大家的帮助!

【问题讨论】:

    标签: html css svg hover fill


    【解决方案1】:

    有三种可能:

    1. 您需要将这两个元素组合到一个共同的<g> 元素中。将鼠标悬停在元素上只能对元素本身和子元素产生影响。
    2. 你可以使用 JavaScript
    3. 您可以使用 SMIL

    CSS

    <style type="text/css">
      #group:hover #to_be_colored_rect {
        fill:red
      }
      /* If you don't want that the color changes when
         hovering over to_be_colored_rect, then use this: */
      #to_be_colored_rect {
        pointer-events:none;
      }
    </style>
    <g id="group">
      <rect width="20" height="20"/>
      <rect id="to_be_colored_rect" width="20" height="20" y="20"/>
    </g>
    

    JavaScript

    又快又脏:

    <rect width="20" height="20" 
      onmousemove="document.getElementById('to_be_colored_rect').setAttribute('fill','red')"
      onmouseout="document.getElementById('to_be_colored_rect').removeAttribute('fill')"/>
    <rect id="to_be_colored_rect" width="20" height="20" y="20"/>
    

    (请将mousemove/mouseout事件处理移至单独的脚本进行生产,这只是演示基本原理。)

    微笑

    <rect width="20" height="20" id="sensitive_rect"/>
    <rect width="20" height="20" y="20">
      <set attributeName="fill" attributeType="CSS" to="red"
        begin="sensitive_rect.mousemove" end="sensitive_rect.mouseout"/>
    </rect>
    

    这是 IMO 一个非常优雅的解决方案,但不幸的是,SMIL 并没有得到非常一致的支持。

    【讨论】:

    • 谢谢大家!我明白了..你们都非常有帮助!谢谢;D
    【解决方案2】:

    我想当您将鼠标悬停在第二个矩形上时,您可以简单地更改第一个矩形的填充属性。

    HTML

    <rect onmouseover="turnred()" onmouseout="turnwhite()" id="margin_left"  width="40" height="420"/> // Replace line 7 with this line
    

    Javascript

    function turnred() {
       document.getElementById("margin_bottom").style.fill="red";
    }
    
    function turnwhite() {
       document.getElementById("margin_bottom").style.fill="white";
    }
    

    【讨论】:

      【解决方案3】:

      这是一个工作页面:http://cssdeck.com/labs/4r8hitea 基本上和 World Bright 使用 jQuery 的代码是一样的

      【讨论】:

      • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
      猜你喜欢
      • 2015-01-29
      • 2012-05-10
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多