javascript: check if mouse is down(pressed) and start counting from zero, after x seconds, it redirect

StackOverflow https://stackoverflow.com/questions/11384463

  •  19-06-2021
  •  | 
  •  

문제

is it possible to detect our mouse when down(pressed), and start counting from zero for a few seconds...and after 5 seconds mousedown, it redirect.

I have found a script that does it, but I am confuse on how to show the second when the mouse is being pressed.

Here it is.

<script type="text/javascript">
/*<![CDATA[*/
document.getElementsByClassName=function(classname){
  var pattern=new RegExp("(^|\s)"+classname+"(\s|$)");
  var results=new Array();
  var d=document.getElementsByTagName('*'), l=d.length;
  for (var k=0; k<l; k++) if (pattern.test(d[k].className)) results.push(d[k]);
  return results;
}

var timer;

function startStuff(el,ii)
{
  var temp=el.innerHTML;
  timer=window.setTimeout('doStuff("'+temp+'");',3000);
}

function stopStuff(el)
{
  window.clearTimeout(timer);
}

function doStuff(l)
{
<?php echo"<html>"; header( 'Location: http://www.google.com' ) ; echo"</html>";?>
}

window.onload=function() {
  var links=document.getElementsByClassName('clicker');
  for (var i=0; i<links.length; i++)
  {
    links[i].onmousedown=function() {startStuff(this)};
    links[i].onmouseup  =function() {stopStuff(this)};
  }
}

/*]]>*/
</script> 

</head>

<body>
<a href="#" class="clicker">Link1</a>
<a href="#">Link2</a>
<a href="#" class="clicker">Link3</a>
</body>
</html>

If possible, I want the second is displayed with images....

도움이 되었습니까?

해결책

I would not use images. Try something like this:

link = document.getElementById('redirect');
counter = document.getElementById('counter');
timeRemaining = 5000;

link.onclick = function(e) {
  e.preventDefault();

  setInterval(function(){
    if (timeRemaining > 0) {
      timeRemaining -= 1000;
      counter.innerHTML = timeRemaining/1000;
    } else {
      window.location = link.href;
    }
  },1000);
};

Full working example:

<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8 />
  <title>Redirect to Google</title>
</head>
<body>
  <a href="http://www.google.com" id="redirect">
    Go to google in <span id="counter">5</span> seconds
  </a>
  <script type="text/javascript">
    link = document.getElementById('redirect');
    counter = document.getElementById('counter');
    timeRemaining = 5000;

    link.onclick = function(e) {
      e.preventDefault();

      setInterval(function(){
        if (timeRemaining > 0) {
          timeRemaining -= 1000;
          counter.innerHTML = timeRemaining/1000;
        } else {
          window.location = link.href;
        }
      },1000);
    };
  </script>
</body>
</html>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top