javascript issue getElementById to modify CSS
javascript issue getElementById to modify CSS
我有一个关于getElementById的问题。
以下是导致问题的 JavaScript 代码部分:
var elmt = document.getElementById("cardSlotsJoueur");
elmt.style.backgroundImage = "url('images/backcard.png')";
我想修改这个 (Css):
#cardSlotsJoueur div {
但它实际上修改了#cardSlotsJoueur {
你能帮我找到一种方法来修改第一个 getElementById 吗?
谢谢!
如果你只想用id=cardSlotsJoueur修改元素中的第一个div,你可以使用这个:
var elmt = document.getElementById("cardSlotsJoueur").getElementsByTagName("div")[0];
要针对#cardSlotsJoueur div
,最好使用querySelector
方法来检索#cardSlotsJoueur
容器的子div 元素:
var elmt = document.querySelector("#cardSlotsJoueur div");
如果您希望#cardSlotsJoueur
下有多个div
元素,那么您需要先将它们全部获取
var elmt = document.querySelectorAll("#cardSlotsJoueur div");
,然后在for
循环中将backgroundImage
设置为每个。
您需要
在#cardSlotsJoueur
中找到div
元素:
var elmt = document.getElementById("cardSlotsJoueur");
var divs = elmt.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
divs[i].style.backgroundImage = "url('images/backcard.png')";
}
执行所需操作的最佳方法可能是使用具有所需样式的类并将其添加到元素中。但作为替代方案,您可以向最后一个样式表添加规则,例如
function addBackground() {
var sheets = document.styleSheets;
// If there are no style sheets, add one
if (!sheets.length) {
document.head.appendChild(document.createElement('style'));
}
// The sheets collection is live, if a new sheet was needed, it's automatically a member
sheets[sheets.length - 1].insertRule('#cardSlotsJoueur div{background-image:url("images/backcard.png")');
}
您可以将其设置为通用:
function addRule(ruleText) {
var sheets = document.styleSheets;
if (!sheets.length) {
document.head.appendChild(document.createElement('style'));
}
sheets[sheets.length - 1].insertRule(ruleText);
}
并像这样称呼它:
addRule('#cardSlotsJoueur div{background-image:url("images/backcard.png")');
相关文章:
- CSS-如何定位内容数据标题
- 窗口大小html css
- 如果文本字段为空,则使用JavaScript应用CSS样式
- 动画.CSS重播
- 有没有一种方法可以防止img get请求使用css或js发生
- CSS表格:从列平移到整个表格宽度
- CKEditor-我在editor.css中的风格是't
- 单击更改图标并通过javascript添加一个css类
- 将CSS应用于printWindow.print();在Javascript中
- 使用CSS或js,使用动态选择器选择任意li的下一个元素
- CSS-若窗口太小,滚动条会出现在“表格”单元格上
- css(或jQuery)悬停时淡入淡出
- 为什么不'在JQuery中找到第二个css选择器的工作
- 为什么 .focus() 不起作用,而 .css(“color”,“red”) 在同一个选择器上起作用
- 如何使用css动画/javascript使具有背景图像的元素出现
- 获取HTML属性中CSS声明的值
- 当我更改Joomla时,它仍然从旧域加载CSS和Javascript
- 如何使用css动画从中心增加边界线
- 谷歌图表-如何更改整个表的css属性
- javascript issue getElementById to modify CSS