簡體   English   中英

如何在同一個元素上設置多個屬性

[英]How to set multiple attributes on the same element

我需要幫助。

我正在創建一個數獨游戲板,我需要畫一些線來划分 3x3 框。 該板是由按鈕制成的,所以我要做的是從第 3 列和第 6 列和行的按鈕中更改邊框顏色。

我面臨的問題是我無法在按鈕上添加 2 個邊框:右側和底部。 Js 代碼一次只添加一個屬性,使用elem.setAttribute 所以我嘗試了一個 function 據說可以讓你添加多個屬性,但它似乎不起作用。

錯誤在哪里?

我感謝您的幫助!

 function createGameboard() { var gameboard = document.getElementById("gameboard"); console.log("creating buttons"); for (var i = 1; i <= 9; i++) { for (var j = 1; j <= 9; j++) { var button = document.createElement("button"); button.id = i + "-" + j; button.className = "buttons"; button.innerHTML = i + "-" + j; if (i == 3 || i == 6) { button.setAttribute("style", "border-bottom: 4px solid black"); } if (j == 3 || j == 6) { button.setAttribute("style", "border-right: 4px solid black"); } if ( (i == 3 && j == 3) || (i == 6 && j == 6) || (i == 3 && j == 6) || (i == 6 && j == 3) ) { setAttributes(button, { "border-right": "4px solid black", "border-bottom": "4px solid black", }); } gameboard.appendChild(button); } } } createGameboard(); function setAttributes(el, attrs) { for (var key in attrs) { el.setAttribute(key, attrs[key]); } }
 body { background-color: #0f4c5c; } h1, h5 { color: white; }.sudoku #gameboard { width: 40vmin; height: 40vmin; display: grid; grid-template-columns: repeat(9, 1fr); gap: 0; }.sudoku button { width: 10vmin; height: 10vmin; background: white; border: 3px solid gray; margin: 0; }
 <body> <div class="container"> <div class="col"> <h1 class="row mx-auto my-3" id="title"> Sudoku </h1> <div class="row my-2 container sudoku"> <div class="gameboard" id="gameboard"></div> </div> </div> </div> </div> </body>

如果您只使用setAttribute進行樣式設置,您可以像這樣修復它:

function setAttribute(element, key, value) {
    element.style[key] = value
}

setAttribute(document.body, "backgroundColor", "red")

請注意,您需要使用 javascript 版本的樣式(背景顏色而不是背景顏色)。

這是因為您覆蓋了該屬性。 您必須連接屬性。 像那樣:

 const d = document.querySelector('button') console.log('before',d) d.setAttribute("style", "border-bottom: 4px solid green;") _tmp = d.getAttribute("style") d.setAttribute("style", _tmp + " border-right: 4px solid black") console.log('after', d)
 <button>1</button>

我使用 function 不僅用於造型,還用於添加/刪除 class。

const setAttributes = (el, object) => {
  for (let key in object) {
    if (key === "addClass") {
      el.classList.add(object[key]);
    } else if (key === "removeClass") {
      el.classList.remove(object[key]);
    } else {
      el.setAttribute(key, object[key]);
    }
  }
};

用法很簡單:

setAttributes(cBtn, {
  class: `${this.prefix}-clear hidden`,
  type: "button",
  "aria-label": this.clearBtnAriLabel,
});

暫無
暫無

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

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