gpt4 book ai didi

javascript - 如何根据输入文本更改类名

转载 作者:行者123 更新时间:2023-11-30 13:26:21 25 4
gpt4 key购买 nike

我需要根据文本值更改输入的 class。当 value 为空时,它应该是默认值,当有 value 时,它应该将类更改为 inputtext

<style>
.inputnotext{ background:#ddd; }
.inputtext{ background:transparent } /* when their is text */
</style>

<form>
<input class="inputnotext" type="text" name="firstname" /><br />
<input class="inputnotext" type="text" name="lastname" />
</form>

<script>
/* script to write ??? */
</script>

最佳答案

这是一个你可以使用的 javascript:

var input = document.getElementsByTagName('input');

keyupHandler = function(input){
if (input.value.length){
input.setAttribute('class', 'inputnotext');
}
else {
input.setAttribute('class', '');
}
}

for (i=0; i<input.length; i++){
input[i].onkeyup = function(){
keyupHandler(this);
}
input[i].onchange = function(){
keyupHandler(this);
}
}

jsFiddle example

最新版本(使用事件监听器和类列表):

var input = document.getElementsByTagName('input');

input.addEventListener('keyup', (e) => {
e.target.classList.toggle("inputnotext", e.target.value );
});

jsFiddle example

关于javascript - 如何根据输入文本更改类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com