【问题标题】:D3.js style and class override not work as my expectationD3.js 样式和类覆盖不能按我的预期工作
【发布时间】:2022-01-15 09:49:36
【问题描述】:

我可以知道为什么我的类“bold-header”样式没有覆盖到表的第一行<tr>?

HTML:

<style>
    .bold-header{
        background-color:navy;
        color:white;
    }
</style>

<table border="1">
    <tr>
        <td>ID</td>
        <td>Name</td>
    </tr>
    <tr>
        <td>001</td>
        <td>John</td>
    </tr>
    <tr>
        <td>002</td>
        <td>Alex</td>
    </tr>
    <tr>         
        <td>003</td>
        <td>Maxwell</td>
    </tr>
</table>

脚本:

d3.select("table").selectAll("td").style("background-color", "lightblue").style("width", "100px");

d3.select("table").select("tr").classed("bold-header", true);

我希望得到这样的结果: my expectation

但它给了我这个: actual result

【问题讨论】:

    标签: javascript css d3.js


    【解决方案1】:

    背景颜色不起作用,因为我们需要在第一行的&lt;td&gt; 元素上设置背景颜色。在您的代码中,您没有选择对应的td's。

    第二行JS代码需要做如下改动:

    d3.select("table").select("tr").selectAll("td").classed("bold-header", true);
    

    更新

    我已经理解了这个问题并更新了代码,这是您的代码无法正常工作的另一个原因,因为您的浅蓝色覆盖了海军颜色。因此,我建议您明智地选择标头 td 标签和正文 td 标签。请看下面的工作代码

    d3.select("table").selectAll("tr:not(:first-child)").style("background-color", "lightblue").style("width", "100px");
    
    d3.select("table").select("tr").classed("bold-header", true);
     .bold-header{
            background-color:navy;
            color:white;
        }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
    <table border="1">
        <tr>
            <td>ID</td>
            <td>Name</td>
        </tr>
        <tr>
            <td>001</td>
            <td>John</td>
        </tr>
        <tr>
            <td>002</td>
            <td>Alex</td>
        </tr>
        <tr>         
            <td>003</td>
            <td>Maxwell</td>
        </tr>
    </table>

    【讨论】:

    • 它不起作用。将类分配给select("tr") 与select("tr").selectAll("td") 相同。实际上海军颜色被前一行JS代码select("table").selectAll("td").style("background-color", "lightblue")覆盖,变成了浅蓝色。
    • 我试图交换两行JS代码,但style("background-color", "lightblue")在背景色中总是比.classed("bold-header", true)具有最高优先级。
    • @HelpMe 请看我在上面的回答中添加的更新
    • 我检查了渲染的 html,发现我没有覆盖,而是让 html 标记具有两个属性(类和背景颜色),这是问题的原因。覆盖应该是相同属性值的更新(即背景颜色)。所以结论可能如你所说Select the tag wisely。
    猜你喜欢
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2018-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多