无法将SVG悬停在rect上

时间:2019-11-21 21:35:31

标签: html css svg

https://jsfiddle.net/dr1vfymn/

我有一个带有两个框的svg元素,当鼠标悬停在上面时,我试图更改其中一个的填充颜色:

#room1:hover {
  fill: #ffcccb;
}
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 100">
    	<rect id="room1" x="0.5" y="0.5" width="93" height="99" style="fill:#fff"/>
    	<path d="M128,44v98H36V44h92m1-1H35V143h94V43Z" transform="translate(-35 -43)"/>
    	<rect id="room2" x="93.5" y="0.5" width="56" height="99" style="fill:#fff"/>
    	<path d="M184,44v98H129V44h55m1-1H128V143h57V43Z" transform="translate(-35 -43)"/>
    </svg>

但是它根本不起作用。可能是什么原因?

1 个答案:

答案 0 :(得分:0)

因为内联CSS是overriding it。解决该问题的一种方法是使用!important

#room1:hover {
  fill: #ffcccb !important;
}
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 100">
    	<rect id="room1" x="0.5" y="0.5" width="93" height="99" style="fill:#fff"/>
    	<path d="M128,44v98H36V44h92m1-1H35V143h94V43Z" transform="translate(-35 -43)"/>
    	<rect id="room2" x="93.5" y="0.5" width="56" height="99" style="fill:#fff"/>
    	<path d="M184,44v98H129V44h55m1-1H128V143h57V43Z" transform="translate(-35 -43)"/>
    </svg>

请注意,通常不会使用!important,所以请不要依赖内联样式:

#room1:hover {
  fill: #ffcccb;
}

#room1,
#room2 {
  fill: #fff;
}
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 100">
    	<rect id="room1" x="0.5" y="0.5" width="93" height="99" />
    	<path d="M128,44v98H36V44h92m1-1H35V143h94V43Z" transform="translate(-35 -43)"/>
    	<rect id="room2" x="93.5" y="0.5" width="56" height="99"/>
    	<path d="M184,44v98H129V44h55m1-1H128V143h57V43Z" transform="translate(-35 -43)"/>
    </svg>