別ページからのページ内リンクやスクロールを行ったときの位置調整css「scroll-margin-top」

Filed under: css — kdcs @ 2025年11月6日 木曜日

#hogeなど要素にidを付けて、その位置までスクロールさせたり別ページからリンクで移動させたりする場合、ページ上部に固定ヘッダーメニューなどがあると重なってしまい#hoge位置が隠れてしまう。

cssの「scroll-margin-top」を使うと#hogeの上にマージンが取れるので、ヘッダーメニュー分以上の縦幅をしていすれば重ならずに済む。
※古いブラウザ向けに代替の記述も併せて指定する

#hoge {
    scroll-margin-top: 50px;
    position: relative;
}
/* フォールバック用(古いブラウザ向け) */
#hoge::before {
  content: "";
  display: block;
  height: 50px;       /* ヘッダーの高さ分 */
  margin-top: -50px;  /* 上にずらす */
  visibility: hidden;
}

Swiperでスライド要素が1つの時、カスタムナビゲーションを非表示にする

Filed under: JavaScript,swiper — kdcs @ 2025年11月6日 木曜日

swiperでページネーションやナビゲーションボタンを.swiperの外側に出して表示位置をカスタマイズしているとき、スライド要素が1つしかない場合はナビゲーションを非表示にしておきたい。

以下のオプション設定で、スライド要素の数を確認し、1つの場合はstyleでdisplay:noe;を付けて非表示にする。
※基本的には、’#eventAd .custom-navigation’これだけをdisplay:noneにすればよい

const swiper2 = new Swiper('.eventAdSlider', {
  loop: true,
  parallax: true, // パララックスさせる
  allowTouchMove: false, // マウスでのスワイプを禁止
  speed: 1500,
  autoplay: {
    delay: 5000, // 5秒ごとに自動再生
    disableOnInteraction: false, // ユーザー操作後も自動再生を継続
  },
  pagination: {
    el: '#eventAd .swiper-pagination',
  },
  navigation: {
    nextEl: '#eventAd .swiper-button-next',
  },
  on: {
    init: function () {
// スライド要素が1つの場合、カスタムナビ非表示(loop:true の場合、クローン要素も含まれるので注意)
      const realSlideCount = this.slides.filter(slide => !slide.classList.contains('swiper-slide-duplicate')).length;
      if (realSlideCount <= 1) {
        document.querySelector('#eventAd .custom-navigation').style.display = 'none';
        document.querySelector('#eventAd .swiper-button-next').style.display = 'none';
        document.querySelector('#eventAd .swiper-button-prev').style.display = 'none';
        document.querySelector('#eventAd .swiper-pagination').style.display = 'none';
      }
    }
  }
});

非表示にする必要が無い場合はこちら

const swiper2 = new Swiper('.eventAdSlider', {
  loop: true,
  parallax: true, // パララックスさせる
  allowTouchMove: false, // マウスでのスワイプを禁止
  speed: 1500,
  autoplay: {
    delay: 5000, // 5秒ごとに自動再生
    disableOnInteraction: false, // ユーザー操作後も自動再生を継続
  },
  pagination: {
    el: '#eventAd .swiper-pagination',
  },
  navigation: {
    nextEl: '#eventAd .swiper-button-next',
  },
});

firefoxでswiperのサムネイルが画面幅変更時にちらつくのを防止する

Filed under: css,swiper — kdcs @ 2025年11月1日 土曜日

レスポンシブデザインで、swiperのサムネイル連動スライドを設置するとfirefoxでサムネイルが画面幅変更時にちらつく。

これを防止する方法

swiperのサムネ要素(divタグに.swiper-slideのクラスが付いている)にcssを足す
※強制的に指定するので、!importantが必要
※複数個所ある場合、「#hogehoge」の部分を合わせる

#hogehoge-thumbnail .swiper-slide {
    transform: none !important;
}

スマホでモーダルメニューを開閉する時にページ内での位置を保持させる

Filed under: JavaScript — kdcs @ 2025年10月9日 木曜日

スマートフォンでページの途中でモーダルメニューを開閉したときにページ内での位置を保持して再表示させる方法。

※コード内でスクロール位置を先に取得して保存させないと、cssのスタイルが先に実行されて「top: 0px」になってしまい、メニューの開閉でページトップに戻されてしまう。

動作OKのコード(scrollアニメ表示版があります)

const trigger = document.querySelector('.globalMenu');
const body = document.body;
const modal = document.getElementById('globalNavArea');
let scrollPosition = 0;

const toggleNav = () => {
  const isOpening = !trigger.classList.contains('is-active'); // 開くかどうかを事前に判定

  if (isOpening) {
    scrollPosition = window.scrollY; // スクロール位置を先に取得
    console.log('保存する scrollPosition:', scrollPosition);
  }

  const isActive = trigger.classList.toggle('is-active');
  body.classList.toggle('is-nav-opened', isActive);
  body.classList.toggle('is-nav-close', !isActive);

  if (isActive) {
    body.style.top = `-${scrollPosition}px`;
    modal.scrollTop = 0;
  } else {
    body.style.top = '';
    window.scrollTo(0, scrollPosition);
  }
};

trigger.addEventListener('click', toggleNav);

こちらはモーダルウィンドウメニューを開いたときにscrollアニメを5秒間表示させるスクリプト
※メニュー開閉時のページ位置保持も修正されています

// 読み込み完了するまでグローバルメニューを非表示にする
// style.cssで「#globalNav」をdisplay: none;にしておく
window.onload = function () {
  document.getElementById('globalNav').style.display = 'block';

// スマホ グローバルメニュー(メニューを開くと5秒間scrollアニメを表示する) ----
const trigger = document.querySelector('.globalMenu');
const body = document.body;
const modal = document.getElementById('globalNavArea');
const scrollNotice = document.querySelector('.sp_block.gnScroll');
let scrollPosition = 0;

let fadeOutTimer = null;
let hideTimer = null;

const toggleNav = () => {
  const isOpening = !trigger.classList.contains('is-active');

  if (isOpening) {
    scrollPosition = window.scrollY;
    console.log('保存する scrollPosition:', scrollPosition);
  }

  const isActive = trigger.classList.toggle('is-active');
  body.classList.toggle('is-nav-opened', isActive);
  body.classList.toggle('is-nav-close', !isActive);

  if (isActive) {
    // スクロールを止める
    body.style.position = 'fixed';
    body.style.top = `-${scrollPosition}px`;
    body.style.left = '0';
    body.style.right = '0';
    modal.scrollTop = 0;

    clearTimeout(fadeOutTimer);
    clearTimeout(hideTimer);

    if (scrollNotice) {
      scrollNotice.style.display = 'block';
      scrollNotice.classList.remove('fade-out');

      fadeOutTimer = setTimeout(() => {
        scrollNotice.classList.add('fade-out');
      }, 5000);

      hideTimer = setTimeout(() => {
        scrollNotice.style.display = 'none';
        scrollNotice.classList.remove('fade-out');
      }, 5500);
    }
  } else {
    // スクロールを戻す
    body.style.position = '';
    body.style.top = '';
    body.style.left = '';
    body.style.right = '';
    window.scrollTo(0, scrollPosition);

    clearTimeout(fadeOutTimer);
    clearTimeout(hideTimer);

    if (scrollNotice) {
      scrollNotice.style.display = 'none';
      scrollNotice.classList.remove('fade-out');
    }
  }
};

trigger.addEventListener('click', toggleNav);

古いios safariでも非jQueryでページトップへのスムーズスクロールをさせる方法

Filed under: css,JavaScript — kdcs @ 2025年10月8日 水曜日

ページトップへのスクロールをスムーズに移動させるためにjQuery+smoothscroll.jsを使用していたが、以下のようにjavascriptだけで動作するようにした。

common.js

const topButton = document.querySelector('#page-top-js');

topButton.addEventListener('click', () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
});

これでは古いiosのsafariでは「behavior: ‘smooth’」がサポートされていないので、「smoothscroll.polyfill」を使う。

footer.php
※common.js内の記述より先に読み込む必要があるのでfooter.phpに記述する。

<script src="https://unpkg.com/smoothscroll-polyfill/dist/smoothscroll.min.js"></script>
<script>
  // ポリフィルを初期化
  smoothscroll.polyfill();
</script>

但し、2022年4月時点で最新のSafari15.4にて、scroll-behaviorが使用できるようになっているので最近のブラウザだけに対応すればよければ以下のcssでOK。

html {
  scroll-behavior: smooth;
}

サイト内検索

カテゴリー

最近の投稿

↑上に戻る