简体   繁体   中英

JavaScript Function Issue (dates)

I'm having issues with my JavaScript code. I need to make code that does the following:

  1. Click an image twice within 3 seconds to make the image disappear
  2. Click it once to reappear

I've got it close to working...I'm just having issues with the date. I don't know how to keep the date from the first click. My code right now is just creating a new start date each click which is what I don't want.

Code thus far:

var imgNext = -1;
var start = new Date ( );

function disappear ()
{
 var end = new Date ();
 imgNext++;

if (imgNext == 2)
{
    document.getElementById("myPicture").style.visibility="visible";
    imgNext = -1;
}
if (imgNext == 1 && (end-start <3000))
{
    document.getElementById("myPicture").style.visibility="hidden";
}
start = new Date ();

}

In the code the image changes even if the clicks are over 3 seconds apart because I'm creating a new START date every time the function is triggered. How do I resolve this?

Here is answer, with a working example: http://jsfiddle.net/yS5bs/2/

document.getElementById("disappear").onclick = function() {
    var lastClick = this.attributes["click-time"],
        click = new Date().getTime(),
        timeout = parseInt(this.attributes["data-timeout"].value);

        if(lastClick && (click - lastClick) < timeout && this.style.opacity == 1) {
            this.style.opacity = 0;
            this.attributes["click-time"].value = null;
            return;
        }
        else {
            this.attributes["click-time"] = click;
        }

        if(this.style.opacity == 0) {
            this.style.opacity = 1;
            this.attributes["click-time"] = null;
            return;
        }
};

basically I am assigning the onclick, and getting the click times, if within the set timeout (milliseconds) then it hides, otherwise, it shows again, as per spec

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