document.getElementById can't select more than one element

前端 未结 4 1212
暗喜
暗喜 2021-01-29 14:01

I\'m working on loading. I have div #loading which is visible. And more divs #message which are hidden. I have js function.

function lo         


        
4条回答
  •  一生所求
    2021-01-29 14:36

    As the others have mentioned ids are unique and can only be used once on a page, so use a class instead. Here I've used querySelectorAll to grab a static list of classes.

    The other issue is that you seem to be trying to use jQuery to fade the elements out, but you're not using jQuery for anything else. I'm going to suggest you CSS transitions. They're easy to use, and you don't have the need of loading a huge library. Here I add new classes fadein and fadeout which (based on your code) increases/reduces the opacity of the specified elements to zero over three seconds.

    function loading() {
      setTimeout(function() {
    
        // use a class for the loader too otherwise the transition
        // won't work properly
        const loader = document.querySelector('.loading');
        loader.classList.add('fadeout');
    
        // grab the elements with the message class
        const messages = document.querySelectorAll('.message');
    
        // loop over them and add a fadeout class to each
        [...messages].forEach(message => message.classList.add('fadein'));
      }, 500);
    }
    
    loading();
    .loading {
      opacity: 1;
    }
    
    .message {
      opacity: 0;
    }
    
    .fadein {
      transition: opacity 3s ease-in-out;
      opacity: 1;
    }
    
    .fadeout {
      transition: opacity 3s ease-in-out;
      opacity: 0;
    }
    Loading
    QWERTY
    123456

提交回复
热议问题