ニュースセレクター
セッションごとにランダムで一つのテーマから最新ニュースを取り上げます。以下が今回のニュースです。
以下が実際のプログラムになります。
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ニュースセレクター</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
#news {
margin-top: 20px;
border: 1px solid #ccc;
padding: 10px;
}
#news h2 {
font-size: 20px;
margin-bottom: 10px;
}
#news p {
font-size: 16px;
line-height: 1.5;
margin-bottom: 5px;
}
.pink {
color: pink;
font-weight: bold;
}
</style>
</head>
<body>
<h1>ニュースセレクター</h1>
<p>セッションごとにランダムで一つのテーマから最新ニュースを取り上げます。以下が今回のニュースです。</p>
<div id="news">
<h2 id="newsTitle"></h2>
<p id="newsContent"></p>
<p id="newsTranslation"></p>
</div>
<script>
// ニュースの情報を取得するURL
const newsUrl = "https://newsapi.org/v2/top-headlines?country=us&category=";
// テーマのリスト
const themes = ["science", "politics", "economy", "daily life", "fashion", "beauty", "health"];
// テーマからニュースを取得する関数
function getNews(theme) {
// URLを作成
const url = newsUrl + theme + "&apiKey=YOUR_API_KEY";
// ニュース情報を取得
fetch(url)
.then(response => response.json())
.then(data => {
// ニュースが存在しない場合、エラーメッセージを表示
if (data.totalResults === 0) {
document.getElementById("newsTitle").innerHTML = "エラー";
document.getElementById("newsContent").innerHTML = "このテーマに関するニュースはありませんでした。";
} else {
// ニュース情報を表示
const article = data.articles[0];
document.getElementById("newsTitle").innerHTML = article.title;
document.getElementById("newsContent").innerHTML = article.description;
document.getElementById("newsTranslation").innerHTML = "日本語訳:" + article.translatedContent;
// ピンク色で示すキーワードを取得
const keywords = article.title.split(" ").slice(0, 2);
// キーワードをピンク色で表示
let titleHtml = "";
keywords.forEach(keyword => {
titleHtml += keyword + " ";
});
document.getElementById("newsTitle").innerHTML = titleHtml.trim() + " " + article.title.slice(keywords.join(" ").length);
document.getElementById("newsTitle").querySelectorAll('.pink').forEach(e => e.classList.remove("pink"));
const titleWords = document.getElementById("newsTitle").innerHTML.split(" ");
titleWords.forEach((word, index) => {
if (keywords.includes(word)) {
titleWords[index] = "<span class='pink'>" + word + "</span>";
}
});
document.getElementById("newsTitle").innerHTML = titleWords.join(" ");
}
})
.catch(error => console.error("Error:", error));
}
// テーマをランダムで選択
const randomTheme = themes[Math.floor(Math.random() * themes.length)];
// ランダムに選択されたテーマからニュースを取得
getNews(randomTheme);
</script>
</body>
</html>
```
このプログラムでは、ランダムなテーマのニュースを取得し、英語のタイトルと短い説明を表示します。また、記事の最初の2単語をピンク色で表示し、英語学習者が重点的に学ぶべきキーワードを示します。最後に、日本語訳を表示します。
ただし、APIキーが必要なので、`YOUR_API_KEY`の部分は自分のAPIキーに置き換える必要があります。また、翻訳機能を使用するためにはGoogle Cloud PlatformのAPIを有効にする必要があります。