Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8582

Nuxtでモーダル実装時に背景がスクロールできてしまう時の対処法

$
0
0

モーダルコンポーネントを作る

<template><transitionname="modal"><divclass="modal-mask"@click="closeModal"><divclass="modal-wrapper"><divclass="modal-container"@click.stop><divclass="modal-contents"><slot></slot></div></div></div></div></transition></template><script>exportdefault{name:"TheModal",methods:{closeModal(){this.$emit("closeModal");}}};</script><stylescoped>省略</style>

ソースコードはこちら

pageコンポーネントのtemplateで以下のように呼び出し

<TheModalv-show="showModal"@closeModal="showModal = false">モーダル
</TheModal>

結果

スクリーンショット 2019-11-19 15.59.08.png

しかし、このままだとモーダルを表示した状態でも後をスクロールすることができてしまう。

スクリーンショット 2019-11-19 16.09.20.png

解決方法

モーダルが表示されているときにbodyタグに以下のクラスを付与する。

modal-body{overflow-y:hidden;position:fixed;}

bodyにクラスを付与するためにグローバルに読み込まれているCSSなどに上のクラスを定義しておく。

ページコンポーネントのhead()に以下を設定する

<script>importLogofrom"~/components/Logo";importTheModalfrom"~/components/TheModal";exportdefault{components:{Logo,TheModal},data(){return{showModal:false};}// ↓追加↓head(){return{bodyAttrs:{class:this.showModal?'modal-body':''}}},};</script>

this.showModalがtrueの時(モーダルが表示されている)にbodyタグに
modal-bodyクラスを付与することができ背景をスクロールさせなくできます。


Viewing all articles
Browse latest Browse all 8582

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>