【问题标题】:svg - style on predefined elements [duplicate]svg - 预定义元素的样式
【发布时间】:2015-07-17 01:30:58
【问题描述】:

我尝试将 css 样式应用于 svg 元素。我想在没有任何脚本的情况下执行此操作。

虽然样式似乎适用于<defs>

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
    "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
    <svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    width="300" height="80">

        <style>
            rect:hover {
                opacity: 0.5;
            }
        </style>

        <defs>  
            <rect id="box" x="0" y="0" width="30" height="20" rx="3" ry="3" style="fill:green;stroke-width:1;stroke:rgb(0,0,0)"/>

            <g id="month">
               <!-- first row -->
               <g transform="translate(50 40)">
                    <use xlink:href='#box'/>
                    <text x="5" y="15" fill="grey">Mon</text>
               </g>
               <g transform="translate(80 40)">
                    <use xlink:href='#box'/>
                    <text x="5" y="15" fill="grey">Thu</text>
                </g>
            </g>
        </defs>

            <use xlink:href='#month'/>

        </svg>

这行得通:

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN"
    "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
    <svg xmlns="http://www.w3.org/2000/svg"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    width="300" height="80">

        <style>
            rect:hover {
                opacity: 0.5;
            }
        </style>

        <rect id="box" x="0" y="0" width="30" height="20" rx="3" ry="3" style="fill:green;stroke-width:1;stroke:rgb(0,0,0)"/>       

    </svg>

有没有办法应用css?是否有其他方法可以将其应用于&lt;defs&gt;-元素?或者有什么解决方法?

【问题讨论】:

    标签: css svg


    【解决方案1】:

    编辑 -- 这是对原始问题的回答,该问题现已更新,回复无效。

    当然,只需给 use 一个类或 ID..

    .box {
      fill: green;
      stroke-width: 1;
      stroke: rgb(0, 0, 0);
    }
    .box:hover {
      fill: red;
    }
    <?xml version="1.0" encoding="UTF-8" standalone="no" ?>
    <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="80">
      <defs>
        <rect id="box" x="0" y="0" width="30" height="20" rx="3" ry="3" />
      </defs>
      <use xlink:href='#box' class="box" />
    </svg>

    【讨论】:

    • 问题是我在&lt;g&gt;-group 中有多个&lt;rect&gt; &lt;defs&gt;,我想单独应用悬停效果。 (我编辑了问题以使其更具体)
    • 不..你不能那样做。您不能“进入”use 到假定的子元素……它们实际上并不存在于use 中……只是像href 一样引用。查看与您的问题重复的链接问题。
    猜你喜欢
    • 1970-01-01
    • 2012-11-20
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    相关资源
    最近更新 更多