簡體   English   中英

某些CSS樣式不適用於SVG

[英]Some CSS styles not working on SVG

我正在研究這個小提琴: https : //jsfiddle.net/thatOneGuy/x2pxx92e/6/

我有以下代碼用於mouseover和out事件:

d3.select('#circleSVG').on('mouseover', function(d) {
  console.log('mouseover')

  d3.select(this).classed('testCircle', true)
  console.log(this)
}).on('mouseout', function(){

  d3.select(this).classed('testCircle', false)
})

testCircle類如下所示:

.testCircle{
  fill: orange;
  opacity:0.25;
}

但是,此類中唯一采用的樣式是不透明度。 它不會改變填充。 知道為什么嗎?

特異性

ID具有比該類更高的指定范圍。

只是使選擇器更具體。 important的不推薦。

#circleSVG {
  fill: red;
  stroke: green;
}

#circleSVG.testCircle{
  fill: orange;
  opacity:0.25;
}

JS小提琴

問題基本上是CSS選擇器的工作方式。

基本上,id選擇器(#)比類選擇器(。)更具體。 因此,類選擇器(.testCircle)中的“ fill:orange”屬性未應用,因為id選擇器(#testCircle)更具體,並且也具有fill屬性。 另一方面,opacity屬性起作用,因為id選擇器未指定該屬性。

要解決此問題,您可以添加“!important”,如下所示:

.testCircle{
  fill: orange !important;
  opacity:0.25;
}

甚至更好的是,使選擇器更具體:

#circleSVG.testCircle{
   fill: orange !important;
   opacity:0.25;
}

您為什么使用JS來做到這一點? 您只能使用CSS。

#circleSVG {
  fill: red;
  stroke: green;
}

#circleSVG:hover {
  fill: orange;
  opacity: 0.25;
}

https://jsfiddle.net/x2pxx92e/11/

您想更改一個類,但也有一個ID來定義svg顏色,因此最好將ID懸停時更改其顏色:

#circleSVG:hover{
  fill: orange;
  opacity:0.25;
}

要通過ID更改顏色,您可以使用

element = document.getElementById(id);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM