ちょっと足しただけ。あると便利かなくらい。
元の形
$(function(){
$('a[href^="#"]').not('a.notscroll').click(function () {
const speed = 500;
const headerHeight = 0;
const href = $(this).attr("href");
const target = $(href == "#" || href == "" ? 'html' : href);
const position = target.offset().top - headerHeight;
$("html, body").animate({ scrollTop: position }, speed, "swing");
return false;
});
});改訂版
$(function(){
$('a[href^="#"], button.js-scroll-btn').not('a.notscroll').click(function (e) {
e.preventDefault();
const speed = 500;
const headerHeight = 0;
const href = $(this).attr("href") || $(this).data("href");
const target = $(href == "#" || href == "" ? 'html' : href);
const position = target.offset().top - headerHeight;
$("html, body").animate({ scrollTop: position }, speed, "swing");
return false;
});
});扱いはこんな感じ
<a href="#xxx">LINK</a>
<button type="button" class="js-scroll-btn" data-href="#xxx">LINK</button>世にある一般的なスムーススクロールにbutton:bを対応させた形。
解説と、実用性が薄いという話
buttonをaの代用にしたい場合、普通はこんな感じ↓
<button type="button" onclick="location.href='#xxx'">LINK</button>jsでリンク機能を付けてるので、スムーススクロールに対応させたかったらonclick自体がじゃまになる。
だから、jsで組み上げるだけでなくbutton自体もいじらなきゃいけない手間がある。
でもって、HTML単体だとリンクとして機能しないわけだし、大人しくaを使えよって話で、SEOの観点からもよろしくない。
微妙ですね。

コメント