【问题标题】:Change button on click for few seconds单击几秒钟更改按钮
【发布时间】:2018-05-18 08:27:30
【问题描述】:

我想在点击几秒钟后更改按钮的图像源。

现在我有这个:

setTimeout(function(){document.getElementById('buttonImg').src='images/button2.png';},5000);

但这会在 5 秒后更改图像,而不是 5 秒。 我不知道如何更改 setTimeout 函数来这样做

【问题讨论】:

    标签: javascript button onclick


    【解决方案1】:

    函数setTimeout 在第二个参数中给出的延迟后执行第一个参数。所以首先立即改变你的形象:

    document.getElementById('buttonImg').src='images/button2.png';
    

    然后在延迟 5 秒(5000 毫秒)后重置为上一个图像:

    setTimeout(function(){
         document.getElementById('buttonImg').src='images/button1.png';
    },5000);
    

    【讨论】:

    • 完成了这项工作,我知道我是怎么错过的。谢谢!
    【解决方案2】:

    你可以做到!

    document.getElementById('buttonImg').src='images/button2.png';
     setTimeout(function() {
         document.getElementById('buttonImg').src='[the source of the original image]';
     } ,5000);
    

    【讨论】:

    • 最好解释一下,这样 OP 才能理解他做错了什么:) 但这就是答案 :)
    【解决方案3】:

    您需要跟踪原始图像,以便在5000 毫秒后替换为原始图像。像这样的,

    function clickBtn(){
     var originalSrc = document.getElementById('buttonImg').src;
     document.getElementById('buttonImg').src = 'https://www.freeiconspng.com/minicovers/submit-button-png-18.png'
      setTimeout(function(){
        document.getElementById('buttonImg').src=originalSrc;
      },5000);
    }
    <img id='buttonImg' src='https://www.freeiconspng.com/minicovers/submit-button-png-9.png' onclick='clickBtn()' />

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 2015-12-29
      相关资源
      最近更新 更多