简体   繁体   中英

Hide/Show image after 2 seconds

So I need to have an image alternatively appear and disappear every 2 seconds, I've been trying using javascript and I've gotten stuck, I feel like it's something so simple but i can't work it out, any help is appreciated.

HTML

<body onload="Show()">
<div align="center">
<img id="image" src="image1.png" height="200" width="200">

JAVASCRIPT

var Cntr=1

function Hide()
{
    Cntr++;
    document.getElementById("image").style.visibility="hidden";
    if (Cntr==2){
        setTimeout("Hide", 2000);
    }
}

function Show() 
{
    Cntr--;
    document.getElementbyId("image").style.visibility="visible";
    if (Cntr==1) {
        setTimeout("Show", 2000);
    }

}

There are a lot of problems with your code.

  1. As Juhana mentioned, you're using setTimeout wrong.

  2. Hide() isn't being called anywhere.

Here's what you can do:

JavaScript

// Store the status of the image. Initially it is 'visible'.
var isVisible = "visible";


function blink() {
    // Toggle the position.
    if(isVisible == "visible") isVisible = "hidden";
    else                       isVisible = "visible";

    // Update it.
    document.getElementById("image").style.visibility = isVisible;

    // Repeat the process every 2 seconds.
    setTimeout(blink, 2000);
}

HTML

<body onload="blink()">...</body>

Working example .

I changed your javscript to this:

var hidden = false;

setInterval(function(){
    document.getElementById("image").style.visibility= hidden ? "visible" : "hidden";
    hidden = !hidden;
},2000);

and deleted the onload function from your <body> tag.

here is a JSFIDDLE as well.

in you setTimeout()s swap show and hide. Also, remove var Cntr. wont need it

function Hide()
{

document.getElementById("image").style.visibility="hidden";

setTimeout("Show()", 2000);

}

function Show() 
{

document.getElementbyId("image").style.visibility="visible";

setTimeout("Hide()", 2000);


}

尝试这个 -

$(function($) { setInterval(function() { if($('#image').is(':visible')) $('#image').hide(); else $('#image').show(); }, 2000); });

Use jQuery instead of raw JS, it is more clean and simple. Use Delay and FadeTo functions with recursion and you are done with one simple function. Call this on page load.

function Flicker(){
    $("#MyImage").delay(1500).fadeTo(300,0).delay(1500).fadeTo(300,1, Flicker);
}

Where: #MyImage is ID of image.

You can see this working @ http://jsfiddle.net/BM3qK/1/

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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