ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

element 表单校验失败定位到指定元素

2026/8/10 13:59:03 拓冰建站 浏览量
element 表单校验失败定位到指定元素
 this.$refs.generateForm.validate(valid => {if (valid) {} else {console.log('表单数据校验失败')this.moveToErr()}

  

moveToErr() {this.$nextTick(() => {let isError = document.getElementsByClassName('is-error')if (isError.length > 0) {const firstError = isError[0];// 检查元素及其子元素是否可获取焦点const focusableElements = firstError.querySelectorAll('input, button, select, textarea, [tabindex]:not([tabindex="-1"])');const hasFocusableChild = focusableElements.length > 0;// 平滑滚动到错误元素firstError.scrollIntoView({behavior: 'smooth',block: 'center'});// 如果有可聚焦子元素则聚焦第一个if (hasFocusableChild) {focusableElements[0].focus();} else {console.log('没有可以聚焦的元素', firstError);}}})},