JS初心者です。
###Bootstrapと同じブレイクポイントで、window.matchMediaを使ったレスポンシブ用のクラス振り分けJS作りました。
xs:0575px767px
sm:576
md:768991px1199px
lg:992
xl:1200px~
Bootstrapがメディアクエリでmin-width:◯◯◯px以上という考え方だったので、それに合わせてます。
###いろんな記事見ながら書いてみてとりあえず動いたのですが、ちょっと気になるところがあります。
- スマホファースト前提で汎用性がない(PCファーストに切り替えるには?)
- ループを多用して処理速度が不安
- 単純に書き方は問題ないか
- Babel使ってビルドしたら大量にwarning出てしまった。(eslintかも)
みなさんならどのように書かれますか?
// breakpoints.js const Breakpoints = (xs,sm,md,lg,xl) => { document.addEventListener('DOMContentLoaded', () => { const mqXs = window.matchMedia('(min-width:' + xs + 'px)'); const mqSm = window.matchMedia('(min-width:' + sm + 'px)'); const mqMd = window.matchMedia('(min-width:' + md + 'px)'); const mqLg = window.matchMedia('(min-width:' + lg + 'px)'); const mqXl = window.matchMedia('(min-width:' + xl + 'px)'); const checkItem = document.getElementsByTagName('html'); const mq = [mqXs,mqSm,mqMd,mqLg,mqXl]; const mqPx = [xs,sm,md,lg,xl]; const mqClass = ['xs','sm','md','lg','xl']; const reloadBreakPoint = () => { for (let i = mq.length - 1; i >= 0; i--) { if (mq[i].matches) { console.log(i); let index = i; for (let j = 0; j <= index; j++) { checkItem[0].classList.add(mqClass[j]); } break; } } }; const checkBreakPoint = (mq) => { const index = mqClass.indexOf(mq); const thisClass = mqPx[index]; const nextClass = mqPx[index + 1]; if (mq == 'xl') { var minWidth = '(min-width:' + thisClass + 'px)'; } else { var minWidth = '(min-width:' + thisClass + 'px)' + ' and (max-width:' + (nextClass - 1) + 'px)'; } window.matchMedia(minWidth).addListener(function(){ if (window.matchMedia('(min-width:' + thisClass + 'px)').matches) { checkItem[0].classList.remove('xl','lg','md','sm','xs'); for (let j = 0; j <= index; j++) { checkItem[0].classList.add(mqClass[j]); } } }); }; // ブレイクポイントの瞬間に発火 checkBreakPoint('xs'); checkBreakPoint('sm'); checkBreakPoint('md'); checkBreakPoint('lg'); checkBreakPoint('xl'); // 初回チェック reloadBreakPoint(); }); return; }; export default Breakpoints;
// common.js import Breakpoints from './_breakpoints.js'; Breakpoints(0,576,768,992,1200);
<!-- 結果 992px ~ 1199pxなら --> <html class="xs sm md lg"> </html>
// エラー eslint 10:36 warning Unexpected string concatenation prefer-template 11:36 warning Unexpected string concatenation prefer-template 12:36 warning Unexpected string concatenation prefer-template 13:36 warning Unexpected string concatenation prefer-template 14:36 warning Unexpected string concatenation prefer-template 25:15 warning 'index' is never reassigned. Use 'const' instead prefer-const 39:9 warning Unexpected var, use let or const instead no-var 39:24 warning Unexpected string concatenation prefer-template 41:9 warning Unexpected var, use let or const instead no-var 41:13 error 'minWidth' is already defined no-redeclare 41:24 warning Unexpected string concatenation prefer-template 43:47 warning Unexpected function expression prefer-arrow-callback 44:31 warning Unexpected string concatenation prefer-template