【问题标题】:Change button styling if element is visible如果元素可见,则更改按钮样式
【发布时间】:2025-12-26 07:45:12
【问题描述】:

我想这是一个非常简单的代码解决方案来修复,但我还没有设法让它发挥作用。 为了给您一些观点,我目前所做的是使用 intl tel 输入进行表单格式化,然后我包含了以下代码(效果很好!)以验证输入;

<span id="valid-msg" class="hide">✓Valid number</span>
<span id="error-msg" class="hide"></span>

<style>
.hide {
        display: none;
}
#valid-msg {
    color: #2b9348;
    
    
}
#error-msg {
        color: #C31014;
    
}
<style>
<!--for validation-->
<script>
var input = document.querySelector("#phone"),
    errorMsg = document.querySelector("#error-msg"),
    validMsg = document.querySelector("#valid-msg");


var updateInputValue = function (event) {
       dialCode.value = "+" + iti.getSelectedCountryData().dialCode;
};
input.addEventListener('input', updateInputValue, false);
input.addEventListener('countrychange', updateInputValue, false);

var errorMap = ["Invalid number", "Invalid country code", "Too short", "Too long", "Invalid number"];

var reset = function() {
  input.classList.remove("error");
  errorMsg.innerHTML = "";
  errorMsg.classList.add("hide");
  validMsg.classList.add("hide");
};

input.addEventListener('blur', function() {
  reset();
  if (input.value.trim()) {
    if (iti.isValidNumber()) {
      validMsg.classList.remove("hide");
    } else {
      input.classList.add("error");
      var errorCode = iti.getValidationError();
      errorMsg.innerHTML = errorMap[errorCode];
      errorMsg.classList.remove("hide");
    }
  }
});

input.addEventListener('change', reset);
input.addEventListener('keyup', reset);
</script>

如果电话号码有效,我想做的是更改提交按钮的样式,我认为这可以通过检查#valid-msg 范围是否可见或没有类来完成。 这是我尝试过的:

<script>
  document.addEventListener('DOMContentLoaded', () => {
    const phoneInput = document.querySelector('#phone');
    const validMsg = document.querySelector('#valid-msg');
    const targetFormButton = document.querySelector('#form-submit');
    if (!phoneInput || !targetFormButton || !validInput) return;

    phoneInput.addEventListener('input', () => {
      const isValid = validMsg.className !== 'hide';
      targetFormButton.classList[isValid ? 'remove' : 'add']('invalid');
      targetFormButton.classList[isValid ? 'add' : 'remove']('valid');
    });
  });
</script> ```

If anyone have suggestions they would be greatly appreciated!

【问题讨论】:

    标签: javascript html jquery css


    【解决方案1】:

    如果您的验证器工作正常,那么您需要的是通过类切换的条件格式:

    const btnSubmit = document.querySelector('#form-submit')
    const phoneInput = document.getElementById('phone')
    const form = document.getElementById('form')
    
    // simplified validation: valid if more
    // than 3 characters long
    const validator = (val) => {
      if (val.length < 3) return false
      return true
    }
    
    // general function to change classes (add & remove)
    // on an element (el)
    const validClassToggle = (addClass, removeClass) => (el) => {
      el.classList.add(addClass)
      el.classList.remove(removeClass)
    }
    
    // creating setInvalid & setValid functions
    const setInvalid = validClassToggle('invalid', 'valid')
    const setValid = validClassToggle('valid', 'invalid')
    
    phoneInput.addEventListener('input', function(e) {
      validator(e.target.value) ?
        setValid(btnSubmit) :
        setInvalid(btnSubmit)
    })
    
    form.addEventListener('submit', function(e) {
      e.stopPropagation()
      e.preventDefault()
      if (validator(phoneInput.value)) {
        console.log("form submitted")
      } else {
        console.log("form not submitted")
      }
    })
    .valid {
      background-color: green;
      color: white;
    }
    
    .invalid {
      background-color: red;
      color: white;
    }
    <form id="form">
      <input id="phone" type="text" /><br />
      <button id="form-submit" type="submit">SUBMIT</button>
    </form>

    【讨论】:

    • 首先非常感谢您的帮助,从我对javascript的非常有限的理解来看,我相信您在这里所做的首先是重做基于长度的验证。这是带有验证功能的代码笔的链接; codepen.io/ralfdev/pen/PoOPBGB 。由于在#valid-msg 上删除了隐藏类,如果该特定跨度不再具有该类,我是否可以将其作为目标并在事件侦听器上触发该函数?