点击更改页面背景颜色页面

时间:2019-11-01 02:36:46

标签: javascript

我试图在单击按钮后将页面颜色的背景更改为“黑色”,并将卡内的文本颜色更改为“白色”。单击该按钮时,颜色仅更改1秒钟,然后恢复为默认颜色。

在下面的代码中,将向您展示一些主要内容

HTML代码:

 <div class="card fontOne">
     <div>
         <hr />
     </div>
     <ul class="card-items item-1">
         <p class="name">Roboto</p>
         <button type="submit" class="font-button"><i class="material- 
         icons">&#xe3ba;</i></button>
     </ul>
     <p class="font-creator">Christina Robertson (12 styles)</p>
     <p class="font-text cardParagraph">Then came the night of
         the first falling star.</p>
 </div>

 <button class="btn-black" id="bMode" onclick="blackMode()"><i class="far fa-circle bg-black"></i></button> 

JS代码:

const changeToBlack = document.getElementById('bMode');
 const text = document.getElementsByClassName('font-text');

 changeToBlack.addEventListener('click', blackMode);

 function blackMode() {
     document.body.style.backgroundColor = "black";
     text.style.color = "white";
 }

我编写了仅更改背景颜色的代码,因为卡片我不知道该怎么做。因此,我尝试只更改1个段落的文本颜色,这也不起作用。

1 个答案:

答案 0 :(得分:0)

let timeStamp;
const changeToBlack = document.getElementById('bMode');
const text = document.getElementById('font-text');
const oriBodyBgColor = document.body.style.backgroundColor;
const oriFontColor = text.style.color;

changeToBlack.addEventListener('click', function() {
  if (timeStamp) {
    clearTimeout(timeStamp)
  }
  document.body.style.backgroundColor = "black";
  text.style.color = "white";
  timeStamp = setTimeout(function() {
    document.body.style.backgroundColor = oriBodyBgColor;
    text.style.color = oriFontColor;
  }, 1000)
});
<!DOCTYPE html>
<html>

<body>
  <div class="card fontOne">
    <div>
      <hr />
    </div>
    <ul class="card-items item-1">
      <p class="name">Roboto</p>
      <button type="submit" class="font-button"><i class="material-
     icons">&#xe3ba;</i></button>
    </ul>
    <p class="font-creator">Christina Robertson (12 styles)</p>
    <p id="font-text" class="font-text cardParagraph">Then came the night of the first falling star.</p>
  </div>

  <button class="btn-black" id="bMode"><i class="far fa-circle bg-black"></i>点我</button>

</body>

</html>

您可以在jsfiddle中运行此代码。 Click me