happylife

ホームページの作り方に関する備忘録です

mb2

jQueryでスムーススクロール

$(function(){
// $(‘a[href^=”#”]’)の^=は前方一致
$(‘a[href^=”#”]’).click(function() {// 属性の値と 前方一致する要素 を選択
var speed = 800; //スクロール速度ミリ秒
var href = $(this).attr(“href”); // アンカーの値取得
// 移動先を取得
var target = $(href == “#” || href == “” ? ‘html’ : href);
var position = target.offset().top;// 移動先を数値で取得
// スムーススクロール
$(‘body,html’).animate({scrollTop:position}, speed, ‘swing’);
return false;
});
});

 

$(‘a[href^=”#”]’)の^=は前方一致

cssで

scroll-behavior: smooth;

があるが、ブラウザ対応がchromとfirefoxのみ

 

if文の場合

$(function(){
// $(‘a[href^=”#”]’)の^=は前方一致
$(‘a[href^=”#”]’).on(‘click’, function() {
var speed = 800; //スクロール速度ミリ秒
var href = $(this).attr(‘href’); //hrefの値(アンカー)取得
var target;
//移動先の取得
if (href == ‘#’ || href == ”) {
var target = $(‘html’);
} else {
var target = $(href);
}
var position = target.offset().top;//移動先を数値で取得
//スムーススクロール
$(‘body,html’).animate({scrollTop:position}, speed, ‘swing’);
return false;//a要素のリンク先移動防ぐ
});
});

Follow me!

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

トラックバックURL: http://subfree.php.xdomain.jp/happy_life/jquery%e3%81%a7%e3%82%b9%e3%83%a0%e3%83%bc%e3%82%b9%e3%82%b9%e3%82%af%e3%83%ad%e3%83%bc%e3%83%ab/trackback/

PAGE TOP