【问题标题】:Why can this function not use opacity?为什么这个功能不能使用不透明度?
【发布时间】:2021-09-15 03:33:25
【问题描述】:

我想通过按下按钮使图像在短时间内稍微透明,然后使其再次正常可见。为什么代码不起作用?

<!DOCTYPE html>
<html>
  <head>
    <style>
    img {
    width: 128px;
    height: 128px;
    padding: 10px;
  }

  img:hover {
    opacity: 0.5;
  }
    </style>
  </head>
  <body>
    <div id="epicenter">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Face-devil-grin.svg/1024px-Face-devil-grin.svg.png" alt="Schwarz" id="black">
    </div>
    <button onclick="test()">Test</button>
    
    <script>
    function sleep(miliseconds) {
    var currentTime = new Date().getTime();
    while (currentTime + miliseconds >= new Date().getTime()) {
    }
    }
    
    function test() {
    document.getElementById("black").style.opacity = "0.33";
    sleep(3000);
    document.getElementById("black").style.opacity = "1";
    }
    </script>
  </body>
</html>

【问题讨论】:

    标签: javascript html css web opacity


    【解决方案1】:

    使用setTimeout 要简单得多。

    function test() {
      const el = document.getElementById('black');
      el.style.opacity = '0.33';
      setTimeout(() => el.style.opacity = '1', 3000);
    }
    img  width: 128px height: 128px padding: 10px; }
    img:hover { opacity: 0.5; }
    <div id="epicenter">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/70/Face-devil-grin.svg/1024px-Face-devil-grin.svg.png" alt="Schwarz" id="black">
    </div>
    <button onclick="test()">Test</button>

    【讨论】:

      【解决方案2】:

      您应该使用 SetTimeout 而不是定义自己的睡眠函数。

      setTimeout(function(){
          document.getElementById("black").style.opacity = 1;
      }, 3000);
      

      用上面的替换你的睡眠函数调用。

      更多详情请参考https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals

      【讨论】:

        猜你喜欢
        • 2020-12-05
        • 2010-10-16
        • 2016-01-10
        • 1970-01-01
        • 1970-01-01
        • 2018-11-04
        • 1970-01-01
        相关资源
        最近更新 更多