使用文本框更改 div 颜色



我正在尝试制作一个小型的javascript程序,其中我有一个最初透明的Div,并且内部包含一个编辑框。但是我希望如果编辑框中的文本不是数字,则透明div 变为粉红色。我该怎么做?我尝试了这样的事情,但没有任何效果:

function proz(){
    var textbox = document.getElementById("nr").value; / nr is editbox
    var div = document.getElementById("proz"); / proz is the transparent div
    if (document.getElementById("nr").value == "a"){ / i tried with if var == "a" but nothing.
        div.setAtribute("id", "proz2"); /here proz 2 is another pink div, trying to overlay first div
    }
}

我正在尝试只使用字母"a"而不是数字来检查是否有任何工作至少......所以请提供任何建议。谢谢!

后期编辑:网页部分:

<body>
<div class="patratpunctat">
<h1><center> Panou centrat </center></h1>
<p> Acest panou va fi centrat vertical si orizontal in pagina.</p>
    <div class="pportocaliu">
        <div class="prosualbastru"> </div>
    </div>
    <!-- -->
    <!-- partea pentru patratul roz cu javascript-->
    <div class="proz">
        <div class="inputt">
        <input type="text" placeholder="Numar interg" name="nrintreg">
        </div>
        <script>
        function check(){
            var textbox = document.getElementById("nrintreg").value;
            if (document.getElementById("nrintreg").value == "a"){
                window.alert('omg')
            }
        }
        </script>
    </div>
</div>

</body>

是的,我正在尝试立即做到这一点。就像那里除了数字之外还有其他东西,使div 变成粉红色。如果是数字,div 保持透明。

这样的东西是你想要的吗?

var textbox = document.getElementById("nr"); // nr is editbox
var div = document.getElementById("proz"); // proz is the transparent div
function proz() {
  div.style.backgroundColor = textbox.value
}
textbox.addEventListener('input', function(evt) {
    proz();
});
#proz {
  height:250px;
  width:250px;
  border:1px solid black;
}
<input type="text" id="nr" />
<div id="proz"></div>

您需要将

更改事件处理程序添加到编辑框(输入,文本区域?(并执行代码。

另外,不要更改id,因为当您的代码再次执行时,它将在getElementById("proz")失败。请改用 css 类来格式化元素。

在这里你有一个工作版本(当输入文本的值为a时,div 将是粉红色的(:

var textbox = document.getElementById("nr");
var div = document.getElementById("proz");
textbox.onkeyup = proz;
function proz() {
    if (textbox.value == "a") {
        div.classList.add("pink");
    } else {
        div.classList.remove("pink");
    }
}
#proz {
  width: 100px;
  height: 100px;
}
#proz.pink {
  background-color: #FF9999;
}
<input id="nr" />
<div id="proz"></div>

我不确定您要实现的目标,但这是我根据您的问题对您可能想要的解释。此代码检查输入是否为数字。如果是,那么它将无能为力。如果它不是数字,它将使文本框周围的透明div 变成粉红色。希望它以某种方式有所帮助

document.getElementById('nr').addEventListener("keyup", proz);
function proz(){
 var textbox = document.getElementById("nr").value; 
 var div = document.getElementById("proz"); 
 if (isNaN(textbox) == true){ 
  document.getElementById("some-div").style.background = "pink";
  }
  else
  {
  document.getElementById("some-div").style.background = ' transparent';
  }
}
#some-div
{
position: absolute;
top: 0;
left: 0;
width:200px; 
height:200px; 
z-index:-1; 
}
<div id = "some-div"> 
<input type="text" id='nr'><br>
  
</div>

最新更新