Javascript隐藏图片

时间:2019-02-13 05:17:57

标签: javascript html css

我经常使用这些抽认卡。最近,我一直在用图片作为答案。但是-我无法隐藏图片。我希望图片在网页启动时被隐藏。

function myShowText(id) {
  document.querySelector('#' + id + ' .answer').style.color = 'black';
}

function myHideText(id) {
  document.querySelector('#' + id + ' .answer').style.color = 'white';
}
.answer {
  border-style: solid;
  border-color: #287EC7;
  color: white;
}
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title> Flashcards VBA </title>
  <rel="stylesheet" href="css/styles.css">
</head>

<body>
  <script src="js/scripts.js"></script>
  <h3> Flashcards </h3>
  <p class="question">
    The first question
  </p>

  <div id="bash_start">
    <p class="answer">
      <img src="image.jpg">
    </p>
  </div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

只需添加以下CSS类:

.hidden {
    display: none;
}

并将类.hidden添加到您的答案中:

<p class="answer hidden">
    <img src="image.jpg">
</p>

然后,只要您想显示答案,就删除此.hidden类:

document.querySelector('.answer').classList.remove('hidden');

这是一个有效的示例:

var button = document.querySelector('button');
var answer = document.querySelector('.answer');

button.addEventListener('click', function() {
  answer.classList.remove('hidden');
});
.hidden {
  display: none;
}
<button type="button">Show answer</button>

<p class="answer hidden">This is the answer</p>

答案 1 :(得分:0)

如果我理解正确,您只是希望在用户加载页面时隐藏图像?在这种情况下,只需在图片visibility: hidden;display: none;

上放一些CSS

然后,您可以在Javascript / Jquery端执行任何要触发它并更改visibility: visible;display: block/inline-block;的事件。

<img class="flashCards" src="https://cdn4.iconfinder.com/data/icons/champions-1/512/Champions-04-512.png">
<button id="validate_btn" onclick="validate()">Validate</button>

<style>

img.flashCards { width: 150px; visibility: hidden; }
</style>

<script>
function validate() {
  var flashCards = document.getElementsByClassName('flashCards');
  //Need a for loop for each image element
  //If only one image use getElementById directly with the style
  for(i=0;i<flashCards.length;i++) {
    flashCards[i].style.visibility = 'visible';
    flashCards[i].style.backgroundColor = 'green';
  }
}
</script>