Promise.catch期间对DOM所做的更改消失了

时间:2019-04-09 18:33:09

标签: javascript css dom dynamic promise

我创建了一个从服务器上获取数据的承诺,当存在网络连接时,它可以完美地工作。

我添加了一个.catch(),以便在服务器不可用时显示DOM元素。触发后,.catch()会起作用,并且会显示DOM元素,但它会在2秒后消失。

我尝试在.catch()中添加DOM元素。我还尝试了将DOM添加到外部函数中并进行调用。我还尝试将外部函数传递给reject()函数。什么都没有。

---样式表---

   #notice {
       width: 100vw;
       height: 100vh;
       opacity: 0;
       animation: fade-in 2s;
       background-color:white;
       z-index: 60;
       display:flex;
       align-items: center;
       text-align: center;
   }

   #notice h1 {
       font-size: 10vh;
       font-family: 'Verdana';
       color: black;
   }

   #notice * {
       position: static;
   }

--- Javascript ---

getSolvedDeck = () => {
  let failed = false;
  new Promise((resolve, reject)=>{
     let xhr = new XMLHttpRequest;
     xhr.open('GET',
              "https://mrlesbomar.com/solitaire/cgi-bin/get_solved_deck.php");
     xhr.onload = () =>{
        if (xhr.status >= 200 && xhr.status < 300) {
           resolve(xhr.response);
        } else {
           reject(xhr.statusText);
        }
     }
     xhr.onerror = () => reject(xhr.statusText);
     xhr.send();
  }).then(stuff=>{
     console.log('Awesomeness');
  }).catch(error=>{
     //Create status screen
     let notice = document.createElement('div');
     notice.id = 'notice';
     notice.innerHTML = '<h1>Error Message</h1><br/>';
     document.getElementsByTagName('main')[0].appendChild(notice);
  });
}

预期结果:出现Promise错误时,屏幕将使用附加的DOM对象填充并一直保留到用户采取措施为止。为用户提供阅读消息的机会。

实际结果:DOM对象被附加到<main>上,充满了屏幕并显示了消息,但在2秒钟内消失了。

问题:如何使在.catch()中执行的操作持久化?

1 个答案:

答案 0 :(得分:1)

该元素持续存在,是CSS导致其消失。动画运行一次,停止,然后我们回到不透明度:0。即使完全没有JS也会发生:

<div id="notice"></div>
#notice {
  width: 100px;
  height: 100px;
  opacity: 0;
  background: blue;
  animation: fade-in 2s;
}
@keyframes fade-in {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

https://codepen.io/anon/pen/YMNaMv?&editable=true

要使#notice停留在屏幕上,请在其样式中添加animation-fill-mode: forwards;

相关问题