简体   繁体   English

如何通过输入值更改div边框颜色?

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

How to change div border-color by input value?如何通过输入值更改div边框颜色?

My Code我的代码

 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>

  • Don't use on* inline JS handlers/attributes.不要使用on*内联 JS 处理程序/属性。 Use Element.addEventListener() .使用Element.addEventListener() JS should in in one place only, and that's either your JavaScript tag or file. JS 应该只在一个地方,那就是你的 JavaScript 标签或文件。
  • getElemntByID should be getElementById getElemntByID应该是getElementById
  • Use input type="color"使用输入type="color"

Create a reusable setBorderColor(Element, color) function:创建一个可重用的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>

try this: run试试这个:运行

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