如何使CSS样式覆盖JavaScript应用的样式 [英] How to make CSS styles override JavaScript applied styles

查看:33
本文介绍了如何使CSS样式覆盖JavaScript应用的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我动态创建一个HTML表,并应用一些样式:

var tbl = document.createElement('table');

tbl.id = "CrewMemberTable";

document.getElementById("CrewMemberPanel").appendChild(tbl);

然后,我在表格中插入行和单元格(为简便起见,在此示例中为三行):

CrewRow = document.getElementById("CrewMemberTable").insertRow(-1);

CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "this text";
CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "some text";
CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "more text";

在最后一个单元格上,我通过javascript应用了一种样式:

CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "more text";
CrewCell.style.backgroundColor = "GREEN";

最后,我的.CSS样式表中有这种样式:

#CrewMemberTable tr:hover {
    background-color: RED !important;
}

严格来说,当我运行它时,我猜没有什么错.它正在执行我要求的操作.

When I run it, strictly speaking, I guess nothing is wrong. It's doing what I asked it to do.

但是-我希望鼠标悬停覆盖整个行,但只覆盖前两个单元格,而最后一个单元格(使用javascript分配背景颜色)仍为绿色.我希望整行都是红色的.

BUT - I want the hover to cover the entire row, but instead it only covers the first two cells, and the last cell, where the background color was assigned in javascript, it remains green. I want the entire row red.

这可能吗?以及如何?

推荐答案

您将需要一个具有更高特异性的选择器,例如

You will need a selector with greater specificity, such as

#CrewMemberTable tr:hover, #CrewMemberTable tr:hover td {
    background-color: RED !important;
}

除了行之外,您还特别希望定位单元格.(如果您愿意,可以向该单元格添加类或ID,以促进更高特异性的定位.)

You will particularly want to target the cell in addition to the row. (If you wanted you could add a class or id to the cell to facilitate higher-specificity targeting.)

有关使用问题中提供的代码结构的工作示例,请参见下面的代码段:

See snippet below for a working example using the code structure you have provided in your question:

var tbl = document.createElement('table');
tbl.id = "CrewMemberTable";
document.getElementById("CrewMemberPanel").appendChild(tbl);
CrewRow = document.getElementById("CrewMemberTable").insertRow(-1);
CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "this text";
CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "some text";
CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "more text";
CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "more text";
CrewCell.style.backgroundColor = "GREEN";

#CrewMemberTable tr:hover, #CrewMemberTable tr:hover td {
        background-color: RED !important;
    }

<div id="CrewMemberPanel"></div>

这篇关于如何使CSS样式覆盖JavaScript应用的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆