У меня есть один ввод на странице; Я пробовал type = "password" и type = "input" . Добавлен только второй вход, чтобы проверить, что происходит, если есть более одного. Также использовал текстовый ввод.
У меня есть кнопка. Если ActiveElement является входом, я Blur () . Если ActiveElement является кнопкой, я возвращаю false ;
, если нет ни одного ActiveElement (по существу, если Body является ActiveElement), то я документирует. Queryselector () для кнопки и триггер. .focus ()
Если я прокомментирую Focus () out, без обновления. Нет обновления, это первое поле сосредоточено очень хорошо.
HTML - это все в форме, подача формы обрабатывается через более позднюю функциональность, я не включаю все это здесь, так как форма не подчиняется в каких -либо других обстоятельствах, за исключением случаев, когда на странице есть единый ввод, и я нажимаю на Eventlistener, и я не сфокусировался на этом, что я пробуждал PRESTER IT/PREE -PERTER IT/PREE -PERTIPER IT/PREE -PERTIPER. />
- использовал jQuery.
- Добавил слушатель событий для фокуса и добавлено event.preventdefault () , а также возвращает false
input
кнопка
handleNextClick(event)}
onKeyDown={(event) => handleNextKeyDown(event)}
ref={buttonNextRef}
type="button"
>
Continue
обработчики кнопок
// Prevent React from triggering two onClicks when a button has focus and Enter is pressed
const handleNextKeyDown = (event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleNextClick(event);
}
};
// Handle the next button click
const handleNextClick = (event) => {
event.preventDefault();
focusFirstInvalidField();
}
Фокус на полевой функции
Примечание. Это имел код, который тестировал для проверки и т. Д., Но я все урисовал, чтобы отладка простой
// Focus on the first invalid/empty field
focusFirstInvalidField: function() {
const invalidFields = document.querySelectorAll('input:enabled:not([type="hidden"]):not([type="button"]), select:enabled');
// if there is only a single field on the page, try adding an eventlistener to listen for the focus event
// then as we focus on the field, try preventDefault() to prevent the page from reloading
// NOTE this doesn't prevent the refresh
if (invalidFields.length === 1) {
invalidFields[0].addEventListener('focus', (event) => {
event.preventDefault();
return false;
});
// This focus causes a refresh.
invalidFields[0].focus();
} else {
// Also have tried looping through all the fields, then focusing. If only one field, refresh happens.
for (const field of invalidFields) {
// As soon as the code hits this line poof refresh. Comment it out, no refresh.
field.focus();
break;
}
}
}
Слушатель событий
document.addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
// Check if we're in a field with focus first, and blur it, then return out of this function.
if (document.activeElement &&
document.activeElement.tagName === 'INPUT' ||
document.activeElement.tagName === 'SELECT' ||
document.activeElement.tagName === 'TEXTAREA'
) {
document.activeElement.blur();
return false;
} else if (document.activeElement.classList.contains('.btn')) {
// If the activeElement is a button, return false. Each action button should have an onKeyPress that handles the enter key and triggers the onClick handler.
return false;
}
const next = document.querySelector('.js-enter-click');
// Click the next button if it exists and is not disabled
next && next.click();
// prevent further activity
return false;
}
});
Подробнее здесь: https://stackoverflow.com/questions/795 ... resh-of-th
Мобильная версия