首页 > web前端 > css教程 > 正文

建立 Abhi ki 新闻网站

王林
发布: 2024-09-03 14:41:32
原创
454 人浏览过

Build a Abhi ki News Website

介绍

开发者们大家好!我很高兴向大家介绍我的最新项目:Abhi ki News。该项目是一个动态新闻网站组件,旨在以干净且用户友好的界面获取和显示新闻文章。这是使用 HTML、CSS 和 JavaScript 增强前端开发技能的绝佳方法,并提供了将外部 API 集成到 Web 应用程序中的实际示例。

项目概况

Abhi ki News 是一个 Web 应用程序,可根据用户输入或预定义类别获取和显示新闻文章。该组件采用现代设计和响应式布局,使其适用于桌面和移动设备。该项目演示了如何创建一个功能性新闻界面,该界面从 API 获取实时数据并以引人入胜的格式呈现。

特征

  • 动态新闻获取:根据用户查询或预定义类别从外部 API 检索并显示新闻文章。
  • 响应式设计:确保新闻界面在所有设备上都具有视觉吸引力。
  • 悬停效果:通过微妙的悬停效果为新闻卡添加交互性。
  • 搜索功能:允许用户通过关键字搜索新闻文章。

使用的技术

  • HTML:提供新闻界面的结构。
  • CSS:设置组件样式以创建具有视觉吸引力和响应式设计。
  • JavaScript:处理数据获取、用户交互并动态更新内容。

项目结构

以下是项目结构的概述:

Abhi-ki-News/
├── index.html
├── style.css
└── script.js
登录后复制
  • index.html:包含新闻组件的 HTML 结构。
  • style.css:包含 CSS 样式以创建引人入胜且响应式的设计。
  • script.js:处理获取和显示新闻文章的逻辑。

安装

要开始该项目,请按照以下步骤操作:

  1. 克隆存储库

    git clone https://github.com/abhishekgurjar-in/Abhi-ki-News.git
    
    登录后复制
  2. 打开项目目录:

    cd Abhi-ki-News
    
    登录后复制
  3. 运行项目:

    • 在网页浏览器中打开index.html文件即可查看新闻界面。

用法

  1. 在网络浏览器中打开应用程序
  2. 单击类别(例如 IPL、金融、政治)以获取与该类别相关的新闻文章。
  3. 使用搜索栏输入相关关键字查找新闻文章。
  4. 与新闻卡互动将鼠标悬停在新闻卡上即可查看悬停效果。

代码说明

超文本标记语言

index.html 文件定义了新闻界面的结构。这是一个片段:

<!DOCTYPE html>
<html lang="en">
<head>
    <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">
</head>
<body>

    <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>
</body>
</html>

登录后复制

CSS

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%);
}

登录后复制

JavaScript

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集成和前端开发的知识。请随意修改和扩展该项目以满足您的需求!

制作人员

  • API来源:新闻API
  • 设计灵感:各种新闻网站

作者

阿布舍克·古贾尔

以上是建立 Abhi ki 新闻网站的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!