Tengo una función que detecta cuando el usuario presiona la tecla TAB. El objetivo principal es verificar si el usuario navega a los elementos de anclaje. Quiero quitarle el atributo de título, pero cuando presione tabulador nuevamente y vaya a otro elemento, quiero restaurar el título nuevamente. En este punto, lo quitaré del foco y estableceré la propiedad del título de datos. Pensé que tal vez podría restaurar el título del atributo de título de datos en el desenfoque. ¿Hay alguna manera de lograrlo?
function checkTabPress (e) { let activeElement if (e.keyCode === 9) { activeElement = document.activeElement if (activeElement.tagName.toLowerCase() === 'a') { activeElement.setAttribute('data-title', activeElement.getAttribute('title')) activeElement.removeAttribute('title') } } } const wrapper = document.getElementById('wrapper') wrapper.addEventListener('keyup', checkTabPress) a:focus { color: red; } <div id="wrapper"> <a title="link 1" href="">link 1</a> <a title="link 2" href="">link 2</a> <a title="link 3" href="">link 3</a> <a title="link 4" href="">link 4</a> </div>Mira esto:
function checkTabPress (e) { let activeElement if (e.keyCode === 9) { activeElement = document.activeElement if (activeElement.tagName.toLowerCase() === 'a') { activeElement.setAttribute('data-title', activeElement.getAttribute('title')) activeElement.removeAttribute('title') } } } const body = document.querySelector('body') body.addEventListener('keyup', checkTabPress) body.addEventListener("blur", function( event ) { var title = event.target.getAttribute('data-title'); if (title) { event.target.setAttribute('title', title) event.target.removeAttribute('data-title') } }, true);Simplemente agregamos un evento de desenfoque y hacemos lo contrario de lo que está haciendo para eliminar el título.
Simplemente puede restaurar títulos en todos los anclajes con cada pulsación de pestaña.
function checkTabPress(e) { let activeElement if (e.keyCode === 9) { // restore titles on all anchors const anchors = document.querySelectorAll('a'); // could be reduced with a parent selector anchors.forEach(function(anchor) { anchor.setAttribute('title', anchor.getAttribute('data-title')) anchor.removeAttribute('data-title') }) activeElement = document.activeElement if (activeElement.tagName.toLowerCase() === 'a') { activeElement.setAttribute('data-title', activeElement.getAttribute('title')) activeElement.removeAttribute('title') } } } const wrapper = document.getElementById('wrapper') wrapper.addEventListener('keyup', checkTabPress) a:focus { color: red; } <div id="wrapper"> <a title="link 1" href="">link 1</a> <a title="link 2" href="">link 2</a> <a title="link 3" href="">link 3</a> <a title="link 4" href="">link 4</a> </div>