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

问题描述 投票:0回答:1

我创建了一个从我的服务器获取数据的承诺,当有网络连接时,它可以很好地工作。

我添加了一个.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()中执行的操作仍然存在?

javascript css dom dynamic promise
1个回答
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;添加到其样式中。

© www.soinside.com 2019 - 2024. All rights reserved.