Last active
November 23, 2024 11:03
-
-
Save H-ymt/4354b44a6ca9a01d405fca83e329799f to your computer and use it in GitHub Desktop.
ビューポートを固定させて狭小デバイスのレスポンシブ対応をするJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ビューポートのサイズを取得する | |
const viewportSize = () => { | |
const vw = window.innerWidth * 0.01 | |
const vh = window.innerHeight * 0.01 | |
document.documentElement.style.setProperty("--vw", `${vw}px`) | |
document.documentElement.style.setProperty("--vh", `${vh}px`) | |
} | |
// 375px以下のビューポートを固定 | |
const viewportFix = () => { | |
const viewport = document.querySelector('meta[name="viewport"]') | |
if (!viewport) return | |
const value = window.outerWidth > 375 ? "width=device-width,initial-scale=1" : "width=375" | |
if (viewport.getAttribute("content") !== value) { | |
viewport.setAttribute("content", value) | |
} | |
} | |
// 375px以下のビューポートに反応する関数 | |
const handleMediaQueryChange = (event) => { | |
if (event.matches) { | |
// 375px以下の場合 | |
viewportSize() | |
viewportFix() | |
} else { | |
// 376px以上の場合(必要なら処理を追加) | |
viewportSize() | |
} | |
} | |
// メディアクエリを作成 | |
const mediaQuery = window.matchMedia("(max-width: 375px)") | |
// 初期実行 | |
handleMediaQueryChange(mediaQuery) | |
// メディアクエリに変更があった際のイベントリスナーを追加 | |
mediaQuery.addEventListener("change", handleMediaQueryChange) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment