How to toggle element visibility without jQuery?

后端 未结 4 1398
猫巷女王i
猫巷女王i 2021-01-12 22:26

I\'m writing an auction template for eBay, hoping that eBay would allow it. Apparently they don\'t because jquery has things like string.replace() etc.

The code is v

相关标签:
4条回答
  • 2021-01-12 22:47

    If you can live without the fading effect, it should be pretty straightforward:

    function changeImage() {
        var image = document.getElementById('coin1');
        image.style.display = (image.style.display == 'none') ? 'block' : 'none';
    }
    
    setInterval(changeImage, 5000);
    

    While fading is cool and all, it's really makes the code a lot more complicated, when we not allowed to use external libraries. Basically, you will need to deal with additional timers, firing with very short intervals, changing the opacity of the target element on each callback.

    If you really want fading, see "Javascript Tutorial - Simple Fade Animation".

    0 讨论(0)
  • 2021-01-12 22:48

    I had issues with the interval approach. This is what I came up with.

    function showHide() {
      var element = document.getElementById('hiddenDetails');
      element.classList.toggle("hidden");
    }
    .hidden {
      display: none;
    }
    
    .show {
      display: block;
    }
    <a href="#" onclick="showHide()">Get Details</a>
    
    <div id="hiddenDetails" class="hidden">What you want to show and hide</div>

    0 讨论(0)
  • 2021-01-12 22:59

    The most basic of fading, not cross-browser compatible (try in Chrome):

    <div id="x" style="background-color: yellow;">
        <a href="#" onclick="fade();">fade me out</a>
    </div>
    
    <script type="text/javascript">
        var val = 1.0;
        function fade()
        {
            document.getElementById('x').style.opacity = val;
            val -= 0.1;
    
            if (val != 0)
            {
                setInterval(fade, 100);
            }
        }
    </script>
    
    0 讨论(0)
  • 2021-01-12 22:59

    You could use classList.toggle on your element:

    <style>
      .hidden { display: none !important; }
    </style>
    
    <script>
      function toggle() {
        document.getElementById('elem').classList.toggle('hidden');
      }
    </script>
    
    <a href="#" onclick="toggle()">Toggle element</a>
    
    <p id="elem">lorem ipsum quid modo tralala</p>
    
    0 讨论(0)
提交回复
热议问题