【问题标题】:Why is the :hover selector not working on this SVG element?为什么 :hover 选择器在这个 SVG 元素上不起作用?
【发布时间】:2019-10-12 11:07:10
【问题描述】:

当我使用选择器 #apple:hover 选择 SVG 元素时,悬停似乎不起作用。为什么这不起作用?

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" display="none">
	<defs>
		<style>
		<![CDATA[
			#apple {
				fill: green;
			}

			#apple:hover {
				fill:red;
			}
		 ]]>
	</style>
		<path id="apple" d="M38.6,30.1c0.1,8.6,7.5,11.4,7.6,11.5c-0.1,0.2-1.2,4.1-3.9,8.1c-2.4,3.5-4.8,6.9-8.7,7
		c-3.8,0.1-5-2.3-9.4-2.3c-4.3,0-5.7,2.2-9.3,2.3c-3.7,0.1-6.6-3.7-9-7.2c-4.9-7-8.6-19.9-3.6-28.6c2.5-4.3,6.9-7,11.7-7.1
		c3.7-0.1,7.1,2.5,9.4,2.5c2.2,0,6.4-3,10.9-2.6c1.9,0.1,7,0.7,10.4,5.6C44.5,19.5,38.5,23,38.6,30.1 M31.5,9.1c2-2.4,3.3-5.7,3-9.1
		c-2.9,0.1-6.3,1.9-8.4,4.3c-1.8,2.1-3.4,5.5-3,8.8C26.2,13.3,29.5,11.5,31.5,9.1"/>
	</defs>
	</svg>
	<svg viewBox="0 0 46.2 56.8" width="47" height="57">
		<use xlink:href="#apple"/>
	</svg>
</body>
</html>

【问题讨论】:

  • 当我将 Id/class 属性放在 元素上而不是路径上时,悬停总是有效。可以试试吗?
  • 我的意思是如果悬停是在引用的 svg 的内部样式中定义的,它就不起作用
  • 如果我不通过 引用元素,@Webify hover 正在处理路径。只需包含内联 svg。但是为什么它不能使用,我在哪里可以阅读它?
  • 因为您将鼠标悬停在 use 元素上,而不是在 apple 上。您的 css 应为:use {fill: green;} use:hover {fill:red;}

标签: css svg hover


【解决方案1】:

像大多数其他人(包括我)一样,你可能并不真正关心解释,所以我会先给你答案,然后再给你解释。

这是你的答案:

#apple {
  fill: green;
}

#apple:hover {
  fill: red;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <svg xmlns="http://www.w3.org/2000/svg" width="47" height="57" viewBox="0 0 46.2 56.8">
    <path id="apple" d="M38.6,30.1c0.1,8.6,7.5,11.4,7.6,11.5c-0.1,0.2-1.2,4.1-3.9,8.1c-2.4,3.5-4.8,6.9-8.7,7
    c-3.8,0.1-5-2.3-9.4-2.3c-4.3,0-5.7,2.2-9.3,2.3c-3.7,0.1-6.6-3.7-9-7.2c-4.9-7-8.6-19.9-3.6-28.6c2.5-4.3,6.9-7,11.7-7.1
    c3.7-0.1,7.1,2.5,9.4,2.5c2.2,0,6.4-3,10.9-2.6c1.9,0.1,7,0.7,10.4,5.6C44.5,19.5,38.5,23,38.6,30.1 M31.5,9.1c2-2.4,3.3-5.7,3-9.1
    c-2.9,0.1-6.3,1.9-8.4,4.3c-1.8,2.1-3.4,5.5-3,8.8C26.2,13.3,29.5,11.5,31.5,9.1"/>
  </svg>
</body>
</html>

这是你的解释:

<svg viewBox="0 0 46.2 56.8" width="47" height="57">
    <use xlink:href="#apple"/>
</svg>

问题基本上只是&lt;use xlink:href="#apple"/&gt;。您也可以只选择 svg 或 use 元素,但假设您想选择该特定路径,您最好的选择是 ^^。

【讨论】:

  • 我在谈论包含在 svg 中的 CSS 悬停在引用它的使用中不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多