簡體   English   中英

如何通過輸入值更改div邊框顏色?

[英]how to change div border-color by input value?

如何通過輸入值更改div邊框顏色?

我的代碼

 function myFunction() { var color = document.getElemntByID("inpx").value; document.getElementById("divx").style.borderColor = color; }
 <!DOCTYPE html> <html> <head> </head> <body> <div id=divx"> </div> <button onClick=""> </button> <script> </script> </body> </html>

  • 不要使用on*內聯 JS 處理程序/屬性。 使用Element.addEventListener() JS 應該只在一個地方,那就是你的 JavaScript 標簽或文件。
  • getElemntByID應該是getElementById
  • 使用輸入type="color"

創建一個可重用的setBorderColor(Element, color)函數:

 const EL = (sel, EL) => (EL||document).querySelector(sel); const setBorderColor = (el, color) => el.style.borderColor = color; const EL_inpx = EL("#inpx"); const EL_divx = EL("#divx"); EL_inpx.addEventListener("input", () => { setBorderColor(EL_divx, EL_inpx.value); }); setBorderColor(EL_divx, EL_inpx.value);
 #divx {border: 10px solid transparent;}
 <input id="inpx" type="color" value="#ff0088"> <div id="divx">test</div>

試試這個:運行

function myFunction() {
  const color = document.getElementById("inpx").value;
  document
    .getElementById("divx")
    .setAttribute("style", "background-color:" + color);
}

 function myFunction() { const color = document.getElementById("inpx").value; document.getElementById("divx").style.borderColor = color; }
 #divx { width: 50px; height: 50px; border-width: 1px; border-style: solid; margin-bottom: 1rem; }
 <html> <body> <div id="divx"></div> <input type="text" value="blue" id="inpx"> <button onClick="myFunction()">Set border color</button> </body> </html>

暫無
暫無

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

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