Declare a JavaScript function which can hide the label of the calling HTML element

前端 未结 5 1204
猫巷女王i
猫巷女王i 2021-01-29 07:01

HTML


5条回答
  •  天命终不由人
    2021-01-29 07:24

    This is a somewhat belated solution, and applies only to more up-to-date/modern browsers (basically, not Internet Explorer before version 8). This solution implements display-toggling (hiding the label when the input is focused, restoring it when the input is blurred):

    Version one, taking advantage of the DOM structure:

    // gets the first 'form' element:
    var parentElement = document.querySelector('form');
    
    function labelToggle (e) {
        // gets the target of the event ('e'),
        // the element that was focused or blurred:
        var self = e.target;
        // if the element has an 'id':
        if (self.id) {
            // get the previous sibling element
            var prev = self.previousElementSibling;
            // if it's 'display: none', change display to 'inline',
            // otherwise change to 'display: none':
            prev.style.display = prev.style.display == 'none' ? 'inline' : 'none';
        }
    }
    
    /* using event-delegation to avoid event-binding with a loop,
       using event-capturing to allow for an ancestor to listen for
       the 'non-bubbling' 'focus' and 'blur' events:
    */
    parentElement.addEventListener('focus', labelToggle, true);
    parentElement.addEventListener('blur', labelToggle, true);
    

    JS Fiddle demo.

    Version two, using the for attribute (rather than the DOM structure):

    // gets the first 'form' element:
    var parentElement = document.querySelector('form');
    
    function labelToggle (e) {
        // gets the target of the event ('e'),
        // the element that was focused or blurred:
        var self = e.target;
        // if the element has an 'id':
        if (self.id) {
            // get the label with the relevant 'for' attribute,
            // using CSS' attribute-equals notation:
            var label = this.querySelector('label[for="' + self.id + '"]');
            // if it's 'display: none', change display to 'inline',
            // otherwise change to 'display: none':
            label.style.display = label.style.display == 'none' ? 'inline' : 'none';
        }
    }
    
    parentElement.addEventListener('focus', labelToggle, true);
    parentElement.addEventListener('blur', labelToggle, true);
    

    JS Fiddle demo.

    Obviously you can call the relevant functions by whatever name you prefer, I call them 'labelToggle' simply because I prefer a function-name to give some indication of what that function does when it's called.

    References:

    • document.querySelector().
    • document.querySelectorAll() compatibility.
    • element.addEventListener().
    • elementTraversal.previousElementSibling.

提交回复
热议问题