jQueryで、ページ内でなく要素内で指定の位置までスムーズにスクロールさせるにはどうしたら良いでしょうか?
あ、か、さ、た、な…というふうに<li>で索引用ボタンを作り、それぞれクリックされると、該当箇所にスクロールするようにしたいのです。スクロールさせるのは<div>で囲った範囲内にしたいです。
下記のようなjQueryを使用してみましたが、ページ全体が動いてしまい、<div>内だけではスクロールできませんでした。
《jQuery》
<script>
$(function() {
$(".index_btn").click(function () {
var i = $(".index_btn").index(this)
var p = $(".contents").eq(i).offset().top;
$(’#contents’).animate({ scrollTop: p },’fast’);
return false;
});
});
</script>
《HTML》
<article>
<ul>
<li class="index_btn">あ行ボタン</li>
<li class="index_btn">か行ボタン</li>
</ul>
<div id="contents">
<div class="contents">
<p>あ行の内容</p>
</div>
<div class="contents">
<p>か行の内容</p>
</div>
</div>
</article>
※imgタグなどは省略しています
みんなの回答 1 件
添付したコードスニペットだと別にjquery.easing.jsが必要だからまだちょっと改造が必要だろうけど、こんな感じでうまくいかない?
var limit = $(ankerName).offset();
num = Math.min(limit.top , $(document).height() - $(window).height());
$('body,html').animate(
{scrollTop: num},
{
duration: 1500,
easing: 'easeOutExpo',
complete : function() {
ankerName = ankerName.replace("#", "");
location.hash = "#"+ankerName;
}
}
)
関連するトピックス