簡體   English   中英

javascript問題getElementById修改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")');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM