简体   繁体   English

如何在没有jQuery的情况下切换元素可见性?

[英]How to toggle element visibility without jQuery?

I'm writing an auction template for eBay, hoping that eBay would allow it. 我正在为eBay写一个拍卖模板,希望eBay能够允许它。 Apparently they don't because jquery has things like string.replace() etc. 显然他们没有,因为jquery有像string.replace()等。

The code is very basic. 代码非常基础。

$(document).ready(function(){

    function changeImage(){
        if($("#coin1").css("display") == "none"){  
            $("#coin1").fadeIn("slow");
        }else{  
            $("#coin1").fadeOut("slow");
        }
    };

    setInterval ( changeImage, 5000 );
});

I basically need to rewrite it in plain Javascript... 我基本上需要在普通的Javascript中重写它...

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" . 如果你真的想要淡化,请参阅“Javascript教程 - 简单淡入淡出动画”

The most basic of fading, not cross-browser compatible (try in Chrome): 最基本的淡入淡出,而不是跨浏览器兼容(在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>

You could use classList.toggle on your element: 您可以在元素上使用classList.toggle

<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>

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM