用途
新着
履歴
分類

JS URLのハッシュ値をUIに活用する

JS URLのハッシュ値をUIに活用する
URLの最後に#をつけて文字列をつけるとページ内のIDのまでページ内で移動します。一瞬で移動せずにスクロールとアコーディオンを組み合わせたUIのサンプルです。

ページ内からのリンクはaタグで書くだけ。

クリックすると、アコーディオンで隠れているコンテンツのところまで、スクロールし、コンテンツを表示します。

直接#をつけてリンクされても正常に動きます。

見せたいコンテンツ3つを黄色の背景とし、上下に青と赤の余白を配置しています。

demo1 demo2 demo3
blue
blue
blue
content1
content2
content3
red
red
red

JavaScript

$(function(){
	var myhash =  location.hash;
	var top_margin = -200;

	if(myhash){
	    $('html, body').animate({
	        scrollTop: $(myhash).length ? $(myhash).offset().top+top_margin : 0
	      }, 1000);
		contentView(myhash);
	}

	$('a').click(function() {
		var demo_id = $(this).attr('href');
		$('.demo_content').hide();
		$('html, body').animate({
			scrollTop: $(demo_id).length ? $(demo_id).offset().top+top_margin : 0
		}, 1000,function(){contentView(demo_id);});
		return false;
	});

	function contentView(myhash){
		$('.demo_content').hide();
		$(myhash+'_body').slideDown();
	}
});

HTML

$(function(){
	var myhash =  location.hash;
	var top_margin = -200;

	if(myhash){
	    $('html, body').animate({
	        scrollTop: $(myhash).length ? $(myhash).offset().top+top_margin : 0
	      }, 1000);
		contentView(myhash);
	}

	$('a').click(function() {
		var demo_id = $(this).attr('href');
		$('.demo_content').hide();
		$('html, body').animate({
			scrollTop: $(demo_id).length ? $(demo_id).offset().top+top_margin : 0
		}, 1000,function(){contentView(demo_id);});
		return false;
	});

	function contentView(myhash){
		$('.demo_content').hide();
		$(myhash+'_body').slideDown();
	}
});

CSS

.blue{
	background-color: blue;
	height:400px;
	color: #FFF;
}
.red{
	background-color: red;
	height:400px;
	color: #FFF;
}
.demo_content{
	display: none;
	height:200px;
	background-color: yellow;
}
#demo_space a{
	border:solid 1px #999;
	padding: 2px;
	margin: 3px;
	display: inline-block;
}
#demo_space a:hover{
	background-color: #EEE;
}
公開 2019-08-07 22:06:43
このページの二次元コード
JS URLのハッシュ値をUIに活用する

人気のサンプル

search -  category -  about
© 2024 kipure
Top