【问题标题】:Transition only working on debug转换仅适用于调试
【发布时间】:2017-07-07 05:09:19
【问题描述】:

以下代码仅在我调试时有效:

function testFunction()
{
  var input = document.getElementById("testInput");
  var button = document.getElementById("testButton");
  
  input.style.transition = "box-shadow 0s";
  input.style.boxShadow = "0px 0px 5px #ff0000";
  input.style.transition = "box-shadow 5s";
  input.style.boxShadow = "0px 0px 0px #000000";
  //input.focus();
}
<input id="testInput"/>
<button id="testButton" onclick="testFunction();">Press me!</button>

我在没有input.focus(); 的情况下尝试过,但这并没有什么不同。当我的调试器在这一点上input.style.boxShadow = "0px 0px 5px #ff0000"; 我可以继续并且它可以工作。当我运行此代码时,为什么我的输入字段没有显示为红色? JSFiddle.

【问题讨论】:

  • 如果没有控制台输出,很难说。我会查看 JSFiddle 并查看是否缺少任何特定内容,因为您只给了我一段代码。
  • @4g0tt3nSou1 控制台不输出任何东西。

标签: javascript css css-transitions transition


【解决方案1】:

我认为是因为您一个接一个地同步设置了2个过渡,浏览器对其进行了优化并在一帧中渲染它们。您可以为第一个转换设置一个较小的持续时间(例如,1ms)并使用transitionend 事件:

function testFunction() {
    var input = document.getElementById("testInput");
    var button = document.getElementById("testButton");

    input.style.transition = "box-shadow 1ms";
    input.addEventListener('transitionend', function() {
        input.style.transition = "box-shadow 5s";
        input.style.boxShadow = "0px 0px 0px #000000";
    }, false);
    input.style.boxShadow = "0px 0px 5px #ff0000";
    //input.focus();
}
<input id="testInput"/>
<button id="testButton" onclick="testFunction();">Press me!</button>

JSFiddle

还可以使用带有 setTimeout(fn, 0) 的旧 hack 来使其工作:

function testFunction() {
    var input = document.getElementById("testInput");
    var button = document.getElementById("testButton");

    input.style.boxShadow = "0px 0px 5px #ff0000";
    setTimeout(function() {
        input.style.transition = "box-shadow 5s";
        input.style.boxShadow = "0px 0px 0px #000000";
    }, 0);
    //input.focus();
}
<input id="testInput"/>
<button id="testButton" onclick="testFunction();">Press me!</button>

JSFiddle

【讨论】:

    【解决方案2】:

    你添加了一条额外的线来设置一个 0px 黑色 box-shadow,但你期望一个红色阴影..

    看看更新的jsfiddle:https://jsfiddle.net/wqt4dehg/4/

    function testFunction()
    {
    	var input = document.getElementById("testInput");
      var button = document.getElementById("testButton");
      
      input.style.transition = "box-shadow 0s";
      input.style.boxShadow = "0px 0px 5px #ff0000";
      input.style.transition = "box-shadow 5s";
      //input.style.boxShadow = "0px 0px 0px #000000";
      //input.focus();
    }
    <input id="testInput"/>
    <button id="testButton" onclick="testFunction();">Press me!</button>

    【讨论】:

    • 我想淡化红色边框。
    猜你喜欢
    • 2018-04-20
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    相关资源
    最近更新 更多