開發者們大家好!我很高興向大家介紹我的最新項目:Abhi ki News。該專案是一個動態新聞網站組件,旨在以乾淨且用戶友好的介面獲取和顯示新聞文章。這是使用 HTML、CSS 和 JavaScript 增強前端開發技能的絕佳方法,並提供了將外部 API 整合到 Web 應用程式中的實際範例。
Abhi ki News 是一個 Web 應用程序,可根據使用者輸入或預先定義類別來取得和顯示新聞文章。該元件採用現代設計和響應式佈局,使其適用於桌面和行動裝置。該專案演示瞭如何創建一個功能性新聞介面,該介面從 API 獲取即時數據並以引人入勝的格式呈現。
以下是項目結構的概述:
Abhi-ki-News/ ├── index.html ├── style.css └── script.js
要開始該項目,請按照以下步驟操作:
複製儲存庫:
git clone https://github.com/abhishekgurjar-in/Abhi-ki-News.git
開啟專案目錄:
cd Abhi-ki-News
運行項目:
index.html 檔案定義了新聞介面的結構。這是一個片段:
<meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Abhi ki News</title> <link rel="stylesheet" href="style.css"> <nav> <div class="main-nav container flex"> <a href="#" onclick="reload()" class="company-logo"> <img src="./assets/logo.png" alt="company logo"> </a> <div class="nav-links"> <ul class="flex"> <li class="hover-link nav-item" id="ipl" onclick="onNavItemClick('ipl')">IPL</li> <li class="hover-link nav-item" id="finance" onclick="onNavItemClick('finance')">Finance</li> <li class="hover-link nav-item" id="politics" onclick="onNavItemClick('politics')">Politics</li> </ul> </div> <div class="search-bar flex"> <input id="search-text" type="text" class="news-input" placeholder="e.g. Science"> <button id="search-button" class="search-button">Search</button> </div> </div> </nav> <main> <div id="loader" class="loader">Loading...</div> <div id="error-message" class="error-message"></div> <div class="cards-container container flex" id="cards-container"> </div> </main> <template id="template-news-card"> <div class="card"> <div class="card-header"> <img src="https://via.placeholder.com/400x200" alt="建立 Abhi ki 新聞網站" id="news-img"> </div> <div class="card-content"> <h3 id="news-title">This is the Title</h3> <h6 class="news-source" id="news-source">End Gadget 26/08/2023</h6> <p class="news-desc" id="news-desc">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Recusandae saepe quis voluptatum quisquam vitae doloremque facilis molestias quae ratione cumque!</p> </div> </div> </template> <script src="script.js"></script>
style.css 檔案對新聞介面進行樣式設置,以確保其具有視覺吸引力和回應能力。以下是一些關鍵樣式:
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@500&family=Roboto:wght@500&display=swap"); * { padding: 0; margin: 0; box-sizing: border-box; } :root { --primary-text-color: #183b56; --secondary-text-color: #577592; --accent-color: #2294ed; --accent-color-dark: #1d69a3; } body { font-family: "Poppins", sans-serif; color: var(--primary-text-color); } p { font-family: "Roboto", sans-serif; color: var(--secondary-text-color); line-height: 1.4rem; } a { text-decoration: none; } ul { list-style: none; } .flex { display: flex; align-items: center; } .container { max-width: 1180px; margin-inline: auto; overflow: hidden; } nav { background-color: #f3faff; box-shadow: 0 0 4px #bbd0e2; position: fixed; top: 0; z-index: 99; left: 0; right: 0; } .main-nav { justify-content: space-between; padding-block: 8px; } .company-logo img { width: 120px; height: 120px; } .nav-links ul { gap: 16px; } .hover-link { cursor: pointer; } .hover-link:hover { color: var(--secondary-text-color); } .hover-link:active { color: red; } .nav-item.active { color: var(--accent-color); } .search-bar { height: 32px; gap: 8px; } .news-input { width: 200px; height: 100%; padding-inline: 12px; border-radius: 4px; border: 2px solid #bbd0e2; font-family: "Roboto", sans-serif; } .search-button { background-color: var(--accent-color); color: white; padding: 8px 24px; border: none; border-radius: 4px; cursor: pointer; font-family: "Roboto", sans-serif; } .search-button:hover { background-color: var(--accent-color-dark); } main { padding-block: 20px; margin-top: 80px; } .cards-container { justify-content: space-between; flex-wrap: wrap; row-gap: 20px; align-items: start; } .card { width: 360px; min-height: 400px; box-shadow: 0 0 4px #d4ecff; border-radius: 4px; cursor: pointer; background-color: #fff; overflow: hidden; transition: all 0.3s ease; } .card:hover { box-shadow: 1px 1px 8px #d4ecff; background-color: #f9fdff; transform: translateY(-2px); } .card-header img { width: 100%; height: 180px; object-fit: cover; } .card-content { padding: 12px; } .news-source { margin-block: 12px; } /* Loader styles */ .loader { display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 1.5rem; color: var(--primary-text-color); } /* Error message styles */ .error-message { color: red; font-size: 1.2rem; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); }
script.js 檔案處理資料取得並動態更新新聞卡。程式碼如下:
const API_KEY = "1d3a0eefa97b499d8fbc4ee93eeb40b7"; const url = "https://newsapi.org/v2/everything?q="; window.addEventListener("load", () => fetchNews("India")); function reload() { window.location.reload(); } async function fetchNews(query) { // Show loader before making the API request showLoader(true); try { const res = await fetch(`${url}${query}&apiKey=${API_KEY}`); if (!res.ok) throw new Error("Network response was not ok"); const data = await res.json(); if (data.articles.length === 0) { showError("No news articles found."); } else { bindData(data.articles); } } catch (error) { showError("Failed to fetch news. Please try again later."); } finally { // Hide loader after the API request completes showLoader(false); } } function bindData(articles) { const cardsContainer = document.getElementById("cards-container"); const newsCardTemplate = document.getElementById("template-news-card"); cardsContainer.innerHTML = ""; articles.forEach((article) => { if (!article.urlToImage) return; const cardClone = newsCardTemplate.content.cloneNode(true); fillDataInCard(cardClone, article); cardsContainer.appendChild(cardClone); }); } function fillDataInCard(cardClone, article) { const newsImg = cardClone.querySelector("#news-img"); const newsTitle = cardClone.querySelector("#news-title"); const newsSource = cardClone.querySelector("#news-source"); const newsDesc = cardClone.querySelector("#news-desc"); newsImg.src = article.urlToImage; newsTitle.innerHTML = article.title; newsDesc.innerHTML = article.description; const date = new Date(article.publishedAt).toLocaleString("en-US", { timeZone: "Asia/Jakarta", }); newsSource.innerHTML = `${article.source.name} · ${date}`; cardClone.firstElementChild.addEventListener("click", () => { window.open(article.url, "_blank"); }); } let curSelectedNav = null; function onNavItemClick(id) { fetchNews(id); const navItem = document.getElementById(id); curSelectedNav?.classList.remove("active"); curSelectedNav = navItem; curSelectedNav.classList.add("active"); } const searchButton = document.getElementById("search-button"); const searchText = document.getElementById("search-text"); searchButton.addEventListener("click", () => { const query = searchText.value; if (!query) return; fetchNews(query); curSelectedNav?.classList.remove("active"); curSelectedNav = null; }); function showLoader(isVisible) { const loader = document.getElementById("loader"); if (isVisible) { loader.style.display = "block"; } else { loader.style.display = "none"; } } function showError(message) { const cardsContainer = document.getElementById("cards-container"); cardsContainer.innerHTML = `<div class="error-message">${message}</div>`; }
您可以在這裡探索該專案的現場演示。
Abhi ki News 是將外部 API 整合到 Web 應用程式並創建響應式、用戶友好的新聞介面的實際範例。我希望這個專案可以幫助您了解更多關於API整合和前端開發的知識。請隨意修改和擴展該專案以滿足您的需求!
阿布舍克·古賈爾
以上是建立 Abhi ki 新聞網站的詳細內容。更多資訊請關注PHP中文網其他相關文章!