{}const=>[]async()letfn</>var
JSWeb

JavaScriptのミニWebアプリケーション:メモ付きアプリケーション

JavaScriptのみでミニWebアプリケーションを作成するためのステップバイステップガイド。このチュートリアルでは、HTML、CSS、JavaScriptを使用してメモアプリケーションを作成し、ブラウザセッション間でデータを保存するためにlocalStorageを接続します。

К

Kodik

著者

6分で読める

こんにちは!👋今日は JavaScriptのミニWebアプリケーションメモアプリ HTML、CSS、JavaScriptを使用して。

このアプリケーションを使用すると、 メモの追加、編集、削除に保存されます localStorage つまり、あなたのメモは ページを再読み込みしても消えない!

検討します アプリケーション作成の各ステップ、その仕組みを理解し、独自のミニWebアプリケーションを作成できるように クリーンなJS.

準備はいいですか?さあ、行きましょう! 🚀

完全なソースコードと追加の改善については、 GitHub.


アプリの機能

当社のノートアプリケーションを使用すると、ユーザーは次のことができます。

  1. タイトルと説明を含むメモを追加します。

  2. ページを再読み込みしてもデータが失われないように、ブラウザにメモを保存します。

  3. 作成したすべてのメモのリストを表示します。

  4. 既存のメモを編集します。

  5. 不要なメモを削除します。

それでは、作成に取り掛かりましょう!


1. HTML構造の作成

HTMLはアプリケーションの構造を担当します。まず、基本的なマークアップを使用してファイル index.html を作成します。

<!DOCTYPE html>
<html lang="ru" dir="ltr">
<head>
  <meta charset="utf-8">
  <title>Приложение для заметок на JavaScript | Coursme</title>
  <link rel="stylesheet" href="style.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- Подключение иконок -->
  <link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.0/css/line.css">
</head>
<body>
  <!-- Всплывающее окно для добавления/редактирования заметок -->
  <div class="popup-box">
    <div class="popup">
      <div class="content">
        <header>
          <p>Добавить новую заметку</p>
          <i class="uil uil-times"></i> <!-- Кнопка закрытия -->
        </header>
        <form action="#">
          <div class="row title">
            <label>Заголовок</label>
            <input type="text" spellcheck="false">
          </div>
          <div class="row description">
            <label>Описание</label>
            <textarea spellcheck="false"></textarea>
          </div>
          <button>Сохранить заметку</button>
        </form>
      </div>
    </div>
  </div>

  <!-- Контейнер для добавления новой заметки -->
  <div class="wrapper">
    <li class="add-box">
      <div class="icon"><i class="uil uil-plus"></i></div>
      <p>Добавить новую заметку</p>
    </li>
  </div>

  <script src="script.js"></script>
</body>
</html>

コードの簡単な説明:

  • popup-box: 新しいメモを作成するためのポップアップウィンドウ。タイトルと説明のフィールドを含むフォームが含まれています。

  • add-box: 新しいメモを追加するためのポップアップウィンドウを開く要素。


2. CSSを使用したスタイル

アプリケーションにスタイルを追加するには、style.cssファイルを作成します。知っておくべき主なスタイルは次のとおりです。

/* Import Google Font - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
body {
  background: #FFB3B3;
}
::selection {
  color: #fff;
  background: #FF6F61;
}
.wrapper {
  margin: 40px;
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(auto-fill, 270px);
}
.wrapper li {
  height: 260px;
  list-style: none;
  border-radius: 8px;
  padding: 15px 18px 18px;
  background: #ffffff;
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease-in-out;
}
.wrapper li:hover {
  transform: translateY(-5px);
}
.add-box,
.icon,
.bottom-content,
.popup,
header,
.settings .menu li {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.add-box {
  cursor: pointer;
  flex-direction: column;
  justify-content: center;
}
.add-box .icon {
  height: 80px;
  width: 80px;
  color: #FF6F61;
  font-size: 42px;
  border-radius: 50%;
  justify-content: center;
  border: 3px dashed #FF6F61;
}
.add-box p {
  color: #FF6F61;
  font-weight: 500;
  margin-top: 18px;
}
.note {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.note .details {
  max-height: 170px;
  overflow-y: auto;
}
.note .details::-webkit-scrollbar,
.popup textarea::-webkit-scrollbar {
  width: 0;
}
.note .details:hover::-webkit-scrollbar,
.popup textarea:hover::-webkit-scrollbar {
  width: 6px;
}
.note .details:hover::-webkit-scrollbar-track,
.popup textarea:hover::-webkit-scrollbar-track {
  background: #f3f3f3;
  border-radius: 20px;
}
.note .details:hover::-webkit-scrollbar-thumb,
.popup textarea:hover::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 20px;
}
.note p {
  font-size: 20px;
  font-weight: 500;
}
.note span {
  display: block;
  color: #626262;
  font-size: 15px;
  margin-top: 6px;
}
.note .bottom-content {
  padding-top: 8px;
  border-top: 1px solid #bbb;
}
.bottom-content span {
  color: #7A7A7A;
  font-size: 13px;
}
.bottom-content .settings {
  position: relative;
}
.bottom-content .settings i {
  color: #7A7A7A;
  cursor: pointer;
  font-size: 16px;
}
.settings .menu {
  z-index: 1;
  bottom: 0;
  right: -5px;
  padding: 6px 0;
  background: #ffffff;
  position: absolute;
  border-radius: 6px;
  transform: scale(0);
  transform-origin: bottom right;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.18);
  transition: transform 0.3s ease;
}
.settings.show .menu {
  transform: scale(1);
}
.settings .menu li {
  height: 28px;
  font-size: 15px;
  margin-bottom: 2px;
  padding: 18px 16px;
  cursor: pointer;
  box-shadow: none;
  border-radius: 0;
  justify-content: flex-start;
}
.menu li:last-child {
  margin-bottom: 0;
}
.menu li:hover {
  background: #f4f4f4;
}
.menu li i {
  padding-right: 8px;
}

.popup-box {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 2;
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.5);
}
.popup-box .popup {
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 3;
  width: 100%;
  max-width: 420px;
  justify-content: center;
  transform: translate(-50%, -50%) scale(0.9);
}
.popup-box,
.popup {
  opacity: 0;
  pointer-events: none;
  transition: all 0.35s ease;
}
.popup-box.show,
.popup-box.show .popup {
  opacity: 1;
  pointer-events: auto;
}
.popup-box.show .popup {
  transform: translate(-50%, -50%) scale(1);
}
.popup .content {
  border-radius: 8px;
  background: #ffffff;
  width: calc(100% - 20px);
  box-shadow: 0 0 18px rgba(0, 0, 0, 0.12);
}
.content header {
  padding: 16px 28px;
  border-bottom: 1px solid #bbb;
}
.content header p {
  font-size: 21px;
  font-weight: 500;
}
.content header i {
  color: #9a9898;
  cursor: pointer;
  font-size: 24px;
}
.content form {
  margin: 18px 28px 40px;
}
.content form .row {
  margin-bottom: 22px;
}
form .row label {
  font-size: 17px;
  display: block;
  margin-bottom: 7px;
}
form :where(input, textarea) {
  height: 52px;
  width: 100%;
  outline: none;
  font-size: 16px;
  padding: 0 16px;
  border-radius: 5px;
  border: 1px solid #aaa;
}
form :where(input, textarea):focus {
  box-shadow: 0 3px 5px rgba(0, 0, 0, 0.15);
}
form .row textarea {
  height: 155px;
  resize: none;
  padding: 10px 16px;
}
form button {
  width: 100%;
  height: 52px;
  color: #fff;
  outline: none;
  border: none;
  cursor: pointer;
  font-size: 17px;
  border-radius: 5px;
  background: #FF6F61;
}

@media (max-width: 660px) {
  .wrapper {
    margin: 12px;
    gap: 12px;
    grid-template-columns: repeat(auto-fill, 100%);
  }
  .popup-box .popup {
    max-width: calc(100% - 12px);
  }
  .bottom-content .settings i {
    font-size: 18px;
  }
}

簡単な説明:

  • 背景:ページに素敵なピンク色の背景を設定しました。

  • add-box: 新しいメモを追加するための「+」アイコン付きの要素。

  • popup-box: メモを追加・編集するときに表示されるポップアップウィンドウ。

スタイルコードは リポジトリ.


3. JavaScript でのアプリケーションロジック

アプリケーションの機能を追加するために、script.jsファイルを作成します。アプリケーションの動作に必要な基本的な機能について説明します。

const addBox = document.querySelector(".add-box"),
    popupBox = document.querySelector(".popup-box"),
    popupTitle = popupBox.querySelector("header p"),
    closeIcon = popupBox.querySelector("header i"),
    titleTag = popupBox.querySelector("input"),
    descTag = popupBox.querySelector("textarea"),
    addBtn = popupBox.querySelector("button");

// ロシア語の月
const months = ["January", "February", "March", "April", "May", "June", "July",
    "August", "September", "October", "November", "December"];

// localStorageに保存されたメモがある場合は取得します
const notes = JSON.parse(localStorage.getItem("notes") || "[]");
let isUpdate = false, updateId;

// 新しいメモを追加するためのウィンドウを開きます
addBox.addEventListener("click", () => {
    popupTitle.innerText = "Add a new note";
    addBtn.innerText = "Add a note";
    popupBox.classList.add("show");
    document.querySelector("body").style.overflow = "hidden";
    if(window.innerWidth > 660) titleTag.focus();
});

// メモの追加/編集ウィンドウを閉じる
closeIcon.addEventListener("click", () => {
    isUpdate = false;
    titleTag.value = descTag.value = "";
    popupBox.classList.remove("show");
    document.querySelector("body").style.overflow = "auto";
});

// すべてのメモを表示する機能
function showNotes() {
    if(!notes) return;
    document.querySelectorAll(".note").forEach(li => li.remove());
    notes.forEach((note, id) => {
        let filterDesc = note.description.replaceAll("\n", '<br/>');
        let liTag = `<li class="note">
                        <div class="details">
                            <p>${note.title}</p>
                            <span>${filterDesc}</span>
                        </div>
                        <div class = "bottom-content">
                            <span>${note.date}</span>
                            <div class="settings">
                                <i onclick="showMenu(this)" class="uil uil-ellipsis-h"></i>
                                <ul class="menu">
                                    <li onclick="updateNote(${id}, '${note.title}', '${filterDesc}')"><i class="uil uil-pen"></i>Edit</li>
                                    <li onclick="deleteNote(${id})"><i class="uil uil-trash"></i>Delete</li>
                                </ ul>
                            </ div>
                        </ div>
                    </ li>`;
        addBox.insertAdjacentHTML("afterend", liTag);
    });
}
showNotes();

// メモの設定メニューを表示する
function showMenu(elem) {
    elem.parentElement.classList.add("show");
    document.addEventListener("click", e => {
        if(e.target.tagName != "I" || e.target != elem) {
            elem.parentElement.classList.remove("show");
        }
    });
}

// メモを削除する
function deleteNote(noteId) {
    let confirmDel = confirm("Are you sure you want to delete this note?");
    if(!confirmDel) return;
    notes.splice(noteId, 1);
    localStorage.setItem("notes", JSON.stringify(notes));
    showNotes();
}

// メモを更新する
function updateNote(noteId, title, filterDesc) {
    let description = filterDesc.replaceAll('<br/>', '\r\n');
    updateId = noteId;
    isUpdate = true;
    addBox.click();
    titleTag.value = title;
    descTag.value = description;
    popupTitle.innerText = "Update note";
    addBtn.innerText = "Update note";
}

// メモの追加または更新
addBtn.addEventListener("click", e => {
    e.preventDefault();
    let title = titleTag.value.trim(),
        description = descTag.value.trim();

    if(title || description) {
        let currentDate = new Date(),
            month = months[currentDate.getMonth()],
            day = currentDate.getDate(),
            year = currentDate.getFullYear();

        let noteInfo = {title, description, date: `${month} ${day}, ${year}`}
        if(!isUpdate) {
            notes.push(noteInfo);
        } else {
            isUpdate = false;
            notes[updateId] = noteInfo;
        }
        localStorage.setItem("notes", JSON.stringify(notes));
        showNotes();
        closeIcon.click();
    }
});

詳細な説明:

  1. addBoxpopupBox: これらの変数は、新しいメモを追加するための要素とポップアップウィンドウを参照します。

  2. フォームを開く機能:「追加」をクリックすると、データ入力フォームが開きます。

  3. メモの追加と保存: [保存]ボタンをクリックすると、データはlocalStorageに保存されます。

  4. メモの表示:保存されたすべてのメモは、showNotes()関数を使用してページに表示されます。

コードの残りの部分は リポジトリ.


結論

これで、JavaScriptのメモを使用した完全なアプリケーションが完成しました。ソースコードをダウンロードして、新しい機能を追加して改善してみてください。開発がうまくいくことを願っています! 🚀

🎯先延ばしをやめよう

記事は気に入った?
実践の時間だ!

Kodikでは読むだけでなく、すぐにコードを書く。理論 + 実践 = 本当のスキル。

即座に実践
🧠AIがコードを説明
🏆修了証

登録不要 • カード不要