Javascript 某些CSS样式不适用于SVG

Javascript 某些CSS样式不适用于SVG,javascript,css,d3.js,svg,Javascript,Css,D3.js,Svg,我正在做这把小提琴: 我有鼠标悬停和退出事件的代码: 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', fals

我正在做这把小提琴:

我有鼠标悬停和退出事件的代码:

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;
}

但是这个类中唯一的风格是不透明度。它不会改变填充。知道为什么吗

问题基本上是CSS选择器如何工作

基本上,id选择器(#)比类选择器(.)更具体。因此,没有应用类选择器(.testCircle)中的“fill:orange”属性,因为id选择器(#testCircle)更具体,并且还具有fill属性。另一方面,由于id选择器没有指定不透明度属性,因此该属性正在工作

要解决此问题,您可以添加“!important”,如下所示:

.testCircle{
  fill: orange !important;
  opacity:0.25;
}
或者更好的是,使选择器更具体:

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

问题基本上是CSS选择器如何工作

基本上,id选择器(#)比类选择器(.)更具体。因此,没有应用类选择器(.testCircle)中的“fill:orange”属性,因为id选择器(#testCircle)更具体,并且还具有fill属性。另一方面,由于id选择器没有指定不透明度属性,因此该属性正在工作

要解决此问题,您可以添加“!important”,如下所示:

.testCircle{
  fill: orange !important;
  opacity:0.25;
}
或者更好的是,使选择器更具体:

#circleSVG.testCircle{
   fill: orange !important;
   opacity:0.25;
}
特异性 ID具有比类更高的特定性

只需使选择器更具体<不建议使用代码>重要信息

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

#circleSVG.testCircle{
  fill: orange;
  opacity:0.25;
}
特异性 ID具有比类更高的特定性

只需使选择器更具体<不建议使用代码>重要信息

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

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

为什么要使用JS来实现这一点?您只能使用css

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

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

为什么要使用JS来实现这一点?您只能使用css

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

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

您希望更改一个类,但您也有一个ID来定义svg颜色,因此最好在ID悬停时更改其颜色:

#circleSVG:hover{
  fill: orange;
  opacity:0.25;
}
要根据ID更改颜色,可以使用

element = document.getElementById(id);

您希望更改一个类,但您也有一个ID来定义svg颜色,因此最好在ID悬停时更改其颜色:

#circleSVG:hover{
  fill: orange;
  opacity:0.25;
}
要根据ID更改颜色,可以使用

element = document.getElementById(id);

@lamelemon legend,我一直在想办法,谢谢you@lamelemon没有必要使用!重要的是,这是一个非常糟糕的问题practice@lamelemonlegend,我一直在想办法,谢谢you@lamelemon没有必要使用!重要的是,这是一个非常糟糕的做法。你能告诉我为什么不推荐吗?在我的实际脱机代码中,我没有可以使用的id,因为有数百个节点,所以我只使用类?
Important
应该作为绝对的最后手段。一旦应用,几乎不可能覆盖againok谢谢,我会做更多的研究。我认为在我的情况下应该没问题:)那家伙对重要的含义给出了一个很好的答案。你能告诉我为什么不推荐它吗?在我的实际脱机代码中,我没有可以使用的id,因为有数百个节点,所以我只使用类?
Important
应该作为绝对的最后手段。一旦应用,几乎不可能覆盖againok谢谢,我会做更多的研究。我认为在我的情况下应该没问题:)@Thatone Guy这是一个关于重要含义的好答案。对不起,我应该说,我的脱机版本需要点击事件而不是悬停对不起,我应该说,我的脱机版本需要点击事件而不是悬停