前提・実現したいこと
Vue.jsでページ内リンクのスムーススクロールを実現したいです。aタグの「次へ」をクリックした時に、
jsスムーススクロール2ページ目の場所へスムーススクロールをさせたいのですが
スムーススクロールができておりません。jsfiddleで試しているのですが、特にエラーは
表示されておらず、このような場合どのように修正していけば良いのか教えていただけないでしょうか。
お願いいたします。
該当のソースコード
○ HTML
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>Vue.js App</title> <style> body { margin: 0; padding: 0; text-align: center; } .slide { width: 100%; height: 100vh; display: flex; align-items: center; justify-content: center; flex-direction: column; } </style> </head> <body> <div class="slide" id="s1"> <h1>jsスムーススクロール1ページ目</h1> <a href="#s2" @click="clickHadle">次へ</a> </div> <div class="slide" id="s2"> <h1>jsスムーススクロール2ページ目</h1> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script> </body> </html>
○javascript
new Vue({ el:'#s1', methods:{ clickHadle:function(){ let smoothScrollRequestId = null; const smoothScrollTo = function(x, y){ const duration = 500; // スムーススクロールが完了するまでの時間 [ms] (必要に応じて変更) const easing = function (t, b, c, d) { // 移動量の計算関数 (同上) return -c *(t/=d)*(t-2) + b; }; const startX = window.pageXOffset, startY = window.pageYOffset; // 初期スクロール位置 const cx = x - startX, cy = y - startY; // 終了値 const startTime = new Date().getTime(); // 開始時刻 let t = 0; // 現在時刻 const scroll = function(){ t = new Date().getTime() - startTime; window.scrollTo(startX + easing(t, 0, cx, duration), startY + easing(t, 0, cy, duration)); if (t < duration) smoothScrollRequestId = requestAnimationFrame(scroll); }; cancelAnimationFrame(smoothScrollRequestId); smoothScrollRequestId = requestAnimationFrame(scroll); }; // クリック時 if (!Element.prototype.matches) Element.prototype.matches = Element.prototype.msMatchesSelector; // https://developer.mozilla.org/ja/docs/Web/API/Element/matches document.addEventListener("click", function(e){ const href = e.target.getAttribute("href"); if (!e.target.matches("a[href^='#'], a[href^='#'] *")) return; // 内部リンク以外は何もしない const dest = href == top ? document.body : document.getElementById(href.slice(1)); // 移動先 if (!dest) return; const y = (function(e){ return e.getBoundingClientRect().top + window.pageYOffset })(dest); // 移動先の、最上位要素からのY座標 smoothScrollTo(0, y); e.preventDefault(); }); } } });
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/02/12 11:44
2019/02/13 04:08
2019/02/13 12:33