我需要根据文本值更改输入的 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);
}
}
最新版本(使用事件监听器和类列表):
var input = document.getElementsByTagName('input');
input.addEventListener('keyup', (e) => {
e.target.classList.toggle("inputnotext", e.target.value );
});
关于javascript - 如何根据输入文本更改类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309114/