首页 文章

在SVG中悬停虚线的事件

提问于
浏览
1

当用户将鼠标悬停在虚线的实体部分上时,带有仅使用 stroke-dasharray 的行(或路径)的SVG似乎会触发CSS和JS悬停事件:https://codepen.io/anon/pen/YeXoZy

是否有一种简单的方法可以在线路的实体或不可见部分悬停时触发JS和CSS事件?

我目前的计划是在相同路径后绘制第二条不可见线,并使用它来检测鼠标事件 . https://codepen.io/anon/pen/BYNgRR这似乎很重,而且我是一个比较缺乏的清洁方式 .

2 回答

  • 1

    这可以通过使用 rect 而不是 line 并使用SVG transformspatterns 来解决 .

    可以在this CodePen看到一个例子 .

    enter image description here

    它基本上起泡到:

    <svg height="210" width="500">
        <defs>
            <pattern id="pattern1"
                    width="10" height="10"
                    patternUnits="userSpaceOnUse"
                    patternTransform="rotate(0 60 60)">
            <line stroke="green" stroke-width="12px" y2="10"/>
            </pattern>
            <pattern id="pattern2"
                    width="10" height="10"
                    patternUnits="userSpaceOnUse"
                    patternTransform="rotate(0 60 60)">
            <line stroke="red" stroke-width="12px" y2="10" stroke="transparent"/>
            </pattern>
        </defs>
        <g transform="rotate(45 60 60)">
            <rect x="0" y="0" width="500" height="5"/>
        </g>
    </svg>
    

    以下CSS:

    rect {
        fill: url(#pattern1)
    }
        rect:hover {
        fill: url(#pattern2)
    }
    
  • 2

    我不确定如何在没有第二个“探测器”线的情况下做到这一点,但如果没有JS,至少可以采用不那么重的方式 .

    切换线的顺序,然后像往常一样使用悬停选择器作为虚线,然后在检测器线的选择器中使用 + 来更改紧随其后的线的属性:

    https://codepen.io/RyanGoree/pen/LQVKBV

相关问题