【问题标题】:How to display API information within a modal?如何在模式中显示 API 信息?
【发布时间】:2022-01-13 14:24:02
【问题描述】:

我想要信息,特别是在图像下方的模式中显示的 cardBody,而不是标题“NASA 每日图片”。

当从 API 加载图像时单击图像时,如何在模态框内的图像下方显示 cardBody 信息,而不是标题“NASA 今日图片”?

const resultsNav = document.getElementById("resultsNav");
const favoritesNav = document.getElementById("favoritesNav");
const imagesContainer = document.querySelector(".images-container");
const saveConfirmed = document.querySelector(".save-confirmed");
const loader = document.querySelector(".loader");

// NASA API
const count = 3;
const apiKey = 'DEMO_KEY';
const apiUrl = `https://api.nasa.gov/planetary/apod?api_key=${apiKey}&count=${count}`;

let resultsArray = [];
let favorites = {};

// Show Content
function showContent(page) {
  window.scrollTo({
    top: 0,
    behavior: "instant"
  });
  if (page === "results") {
    resultsNav.classList.remove("hidden");
    favoritesNav.classList.add("hidden");
  } else {
    resultsNav.classList.add("hidden");
    favoritesNav.classList.remove("hidden");
  }
  loader.classList.add("hidden");
}

// Create DOM Nodes
function createDOMNodes(page) {
  const currentArray =
    page === "results" ? resultsArray : Object.values(favorites);
  currentArray.forEach((result) => {
    // Card Container
    const card = document.createElement("div");
    card.classList.add("card");


    // Link that wraps the image
    const link = document.createElement("a");

    // link.href = result.hdurl;  -- full size image display when clicked

    // Get the modal
    var modal = document.getElementById("myModal");

    // Get the image and insert it inside the modal - use its "alt" text as a caption
    var img = document.getElementById("myImg");
    var modalImg = document.getElementById("img01");

    var captionText = document.getElementById("caption");
    img.onclick = function() {
      modal.style.display = "block";


      modalImg.src = event.target.src;
      captionText.innerHTML = event.target.alt;



    }

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
      modal.style.display = "none";
    }

    // Image
    const image = document.createElement("img");
    image.src = result.url;
    image.alt = "NASA Picture of the Day";
    image.loading = "lazy";
    image.classList.add("card-img-top");

    // Card Body
    const cardBody = document.createElement("div");
    cardBody.classList.add("card-body");

    // Card Title
    const cardTitle = document.createElement("h5");
    cardTitle.classList.add("card-title");
    cardTitle.textContent = result.title;

    // Save Text
    const saveText = document.createElement("p");
    saveText.classList.add("clickable");
    if (page === "results") {
      saveText.textContent = "Add To Favorites";
      saveText.setAttribute("onclick", `saveFavorite('${result.url}')`);
    } else {
      saveText.textContent = "Remove Favorite";
      saveText.setAttribute("onclick", `removeFavorite('${result.url}')`);
    }

    // Card Text
    const cardText = document.createElement("p");
    cardText.textContent = result.explanation;

    // Footer Conatiner
    const footer = document.createElement("small");
    footer.classList.add("text-muted");

    // Date
    const date = document.createElement("strong");
    date.textContent = result.date;

    // Copyright
    const copyrightResult =
      result.copyright === undefined ? "" : result.copyright;
    const copyright = document.createElement("span");
    copyright.textContent = ` ${copyrightResult}`;

    // Append everything together
    footer.append(date, copyright);
    cardBody.append(cardTitle, saveText, cardText, footer); //hide to make image display
    link.appendChild(image);
    card.append(link); // hide cardBody

    // Append to image container
    imagesContainer.appendChild(card);
  });
}

// Update the DOM
function updateDOM(page) {
  // Get favorites from local storage
  if (localStorage.getItem("nasaFavorites")) {
    favorites = JSON.parse(localStorage.getItem("nasaFavorites"));
  }
  imagesContainer.textContent = "";
  createDOMNodes(page);
  showContent(page);
}

// Get 10 images from NASA API
async function getNasaPictures() {
  // Show Loader
  loader.classList.remove("hidden");
  try {
    const response = await fetch(apiUrl);
    resultsArray = await response.json();
    updateDOM("results");
  } catch (error) {
    // Catch Error Here
  }
}

// Add result to favorites
function saveFavorite(itemUrl) {
  // Loop through the results array to select favorite
  resultsArray.forEach((item) => {
    if (item.url.includes(itemUrl) && !favorites[itemUrl]) {
      favorites[itemUrl] = item;
      // Show save confirmation for 2 seconds
      saveConfirmed.hidden = false;
      setTimeout(() => {
        saveConfirmed.hidden = true;
      }, 2000);
      // Set Favorites in Local Storage
      localStorage.setItem("nasaFavorites", JSON.stringify(favorites));
    }
  });
}

// Remove item from favorites
function removeFavorite(itemUrl) {
  if (favorites[itemUrl]) {
    delete favorites[itemUrl];
    localStorage.setItem("nasaFavorites", JSON.stringify(favorites));
    updateDOM("favorites");
  }
}

// On Load
getNasaPictures();
.container {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 3% 1fr 0.1fr;
  gap: 0px 0px;
  grid-auto-flow: row;
  grid-template-areas:
    "header"
    "content"
}



.hero {
  grid-area: hero;
  background-color: blue;
}

.content {
  grid-area: content;
  background-color: orange;
  align-self: center;
  justify-self: center;
}



html {
  box-sizing: border-box;
}

body {
  margin: 0;
  background: whitesmoke;
  overflow-x: hidden;
  font-family: Verdana, sans-serif;
  font-size: 1rem;
  line-height: 1.8rem;
}


.loader {
  position: fixed;
  z-index: 40;
  background: whitesmoke;
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Navigation */
.navigation-container {
  position: fixed;
  top: 0;
}

.navigation-items {
  display: flex;
  justify-content: center;
}

.background {
  background: whitesmoke;
  position: fixed;
  right: 0;
  width: 100%;
  height: 60px;
  z-index: -1;
}

.clickable {
  color: #0b3d91;
  cursor: pointer;
  user-select: none;
}

.clickable:hover {
  color: #fc3d21;
}

/* Images Container */
.images-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

.card {
  margin: 10px 10px 10px;
  width: 300px;
  height: 300px;
}

.card-img-top {
  width: 300px;
  height: 300px;

}

.card-body {
  padding: 20px;
}

.card-title {
  margin: 10px auto;
  font-size: 24px;
}

/* Save Confirmation */
.save-confirmed {
  background: white;
  padding: 8px 16px;
  border-radius: 5px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  position: fixed;
  bottom: 25px;
  right: 50px;
  z-index: 500;
}

/* Hidden */
.hidden {
  display: none;
}

.brand {
  float: right;
}

.fave {
  margin-right: 50%;
}











#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

/* #myImg:hover {opacity: 0.7;} */

/* The Modal (background) */
.modal {
  display: none;
  /* Hidden by default */
  position: fixed;
  /* Stay in place */
  z-index: 1;
  /* Sit on top */
  padding-top: 100px;
  /* Location of the box */
  left: 0;
  top: 0;
  width: 100%;
  /* Full width */
  height: 100%;
  /* Full height */
  overflow: auto;
  /* Enable scroll if needed */
  background-color: rgb(0, 0, 0);
  /* Fallback color */
  background-color: rgba(0, 0, 0, 0.9);
  /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

/* Caption of Modal Image */
#caption {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}

/* The Close Button */
.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px) {
  .modal-content {
    width: 100%;
  }
}
<!-- Loader -->
<div class="loader hidden">
  <img src="rocket.svg" alt="Rocket Icon" />
</div>

<!-- Container -->

<div class="container">
  <div class="header">
    <div class="navigation-container">
      <span class="background"></span>
      <!-- Results Nav -->
      <span class="navigation-items" id="resultsNav">
      </span>
      <!-- Favorites Nav -->
      <span class="navigation-items hidden" id="favoritesNav">

      </span>
    </div>
  </div>


  <div class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="column">
          <div id="myImg" alt="Snow" class="images-container"></div>
        </div>
      </div>
    </div>
  </div>



  <!-- The Modal -->
  <div id="myModal" class="modal">
    <span class="close">&times;</span>
    <img class="modal-content" id="img01">
    <div id="caption"></div>
  </div>


</div>

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    每个图像对象都有以下键:

      copyright
      date
      explanation
      hdurl
      media_type
      service_version
      title
      url
    

    目前您正在使用这段代码来渲染图像:

    // Image
        const image = document.createElement("img");
        image.src = result.url;
        image.alt = "NASA Picture of the Day";
        image.loading = "lazy";
        image.classList.add("card-img-top");
    

    image.alt = "NASA Picture of the Day" 替换为image.alt = result.title,它应该可以满足您的需求!

    【讨论】:

    • 谢谢!新手问题,但是我如何将例如标题和解释结合在一起以显示在模式上?还有一个保存收藏夹功能。有没有办法在模态中实现它?
    • 或者更好的显示cardBody?
    • 抱歉,这需要一段时间,我没有看到您发表评论的通知。但是,如果您看一下:captionText.innerHTML = event.target.alt; 您正在将内容设置为图像的 Alt,如果您想使用解释,只需将其替换为您想要的信息。它也是一个 innerHTML 属性,因此您可以创建自定义 HTML 格式并使用您想要的所有信息,例如:innerHTML = &lt;p&gt;This&lt;/p&gt;&lt;p&gt;That&lt;/p&gt; 与您选择的模板
    • 为了实现喜欢的功能,您可能需要使用本地存储或 cookie 以在刷新时持久保存信息,但这不是 100% 可靠的,理想情况下您会将这些信息存储在某种后端中的另一项服务
    • @user8 jsfiddle.net/helrabelo/dr8oe5n6/1 给了你一点帮助,不过建议你搜索一下如何使用javascript设置Cookies。还搜索 eventListeners 以便您可以在按钮单击时添加一个功能以添加到收藏夹,按照您的方法,这将是在模态框上添加按钮 HTML,其 ID 可用于 JS 文件来处理点击收藏夹。
    猜你喜欢
    • 2021-07-18
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    相关资源
    最近更新 更多