亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

更改類時不應用 D3 css

更改類時不應用 D3 css

Helenr 2023-09-07 16:10:39
我有一個條形圖,我想在單擊條形圖時更改顏色。我想在單擊的元素上設置 CSS 類。一切正常,除了填充樣式(單擊的欄的顏色)沒有改變,但應用了綠色描邊。我不明白為什么。這是單擊圖表最后一個柱之前和之后的屏幕 這就是我想要實現的目標這是我的代碼的一部分,有什么建議嗎?JS//CREATE THE BAR CHARTvar bars = d3  .select("#bars")  .selectAll("rect")  .data(data);bars  .enter()  .append("rect")  .attr("x", function(d) {    return xScale(d.year);  })  .attr("y", function(d) {    return yScale(d.cost);  })  .attr("width", xScale.bandwidth)  .attr("height", function(d) {    return height - yScale(d.cost);  })  .style("fill", function(d) {    return colorScale(d.cost);  });//EVENT ON CLICKd3.select("#bars")  .selectAll("rect")  .on("click", function() {    //reset the previus bar selected    d3.select("#bars")      .select(".selected")      .classed("selected", false)      .style("fill", function(d) {        return colorScale(d.cost);  //reset the original color      });    //set the current bar as selected    d3.select(this).classed("selected", true);  });CSS.selected {  fill: red;  stroke: green;  stroke-width: 3;}
查看完整描述

1 回答

?
不負相思意

TA貢獻1777條經驗 獲得超10個贊

一般來說,屬性樣式會被使用選擇器的 CSS 樣式覆蓋,而 CSS 樣式又會被內聯 CSS 樣式覆蓋。

  • .attr("fill", "blue")設置屬性fill="blue";

  • .selected { fill: "red"; }應用風格fill: red;

  • .style("fill", "green")設置屬性style="fill: green;",內聯樣式。

如果將所有這些應用于同一元素,則最后一個優先。通過取消選擇先前選擇的欄,您可以賦予它.style("fill",從而覆蓋任何潛在的未來樣式。我建議檢查您是否真的需要應用這些樣式,.attr()如果需要就使用。

我在下面添加了一個小展示柜。

let settings = {

  attr: false,

  class: false,

  style: false,

};

draw();


function draw() {

  d3.select("rect")

    .attr("fill", settings.attr ? "red" : null)

    .attr("class", settings.class ? "blue" : "")

    .style("fill", settings.style ? "green" : null);

}


d3.selectAll("[type='checkbox']")

  .on("change", function() {

    settings[this.getAttribute("id")] = this.checked;

    draw();

  });

.blue {

  fill: blue;

}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<div>

  <input type="checkbox" id="attr"/><label for="attr">attr</label>

  <input type="checkbox" id="class"/><label for="class">class</label>

  <input type="checkbox" id="style"/><label for="style">style</label>

</div>

<svg>

  <rect width="30" height="30"></rect>

</svg>


查看完整回答
反對 回復 2023-09-07
  • 1 回答
  • 0 關注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號