• RSS

[JS]「jQuery Text Resizer」と「jQuery Cookie」を利用して文字サイズを大中小と変更する

  • このエントリーをはてなブックマークに追加
  • follow us in feedly

企業サイトであれば「文字の大中小」ボタンをクリックしてページ内のフォントサイズを変更することがよくあると思いますが、jQuery プラグイン jQuery Text Resizer を使えば手軽に実装できます。

また、jQuery Cookie と併用することで、現在のフォントサイズ(の状態)を Cookie に保持できるので、サイト内の別ページへ遷移したりページを離脱してもう一度戻ってきた場合でもサイズを維持することができます。

目次

jQuery Text Resizer と jQuery Cookie のダウンロード

以下のページより、jQuery Text Resizer Plugin ファイルをダウンロードします。

jQuery Cookie はこちら。


jQuery Text Resizer と jQuery Cookie の設置

jquery.textresizer.jsjquery.cookie.js を、jquery ファイルと一緒に <head> 内に設置します。
<script type="text/javascript" src="/jquery.min.js"></script>
<script type="text/javascript" src="/jquery.cookie.js"></script>
<script type="text/javascript" src="/jquery.textresizer.js"></script>
<script type="text/javascript">
jQuery(document).ready( function() {
	jQuery( "#textsize a" ).textresizer({
		target: "#contents",
		type: "cssClass",
		sizes: [ "f1", "f2" ,"f3" ]
	});
});
</script>

オプション

target: で文字サイズ変更の領域(対象要素)を指定します。

また、type: には fontSize cssClass css の3種類あり、それぞれ sizes: に指定する値が異なります。


type:”fontSize”

type:"fontSize" の場合、sizes にはフォントサイズを直接指定します。
シンプルで分かりやすいです。
<script type="text/javascript">
jQuery(document).ready( function() {
	jQuery( "#textsize a" ).textresizer({
		target: "#contents",
		type: "fontSize",
		sizes:	[
			"10px",
			"12px",
			"14px" 
				]
	});
});
</script>


type:”cssClass”

type:"cssClass" の場合、sizes はクラス名になります。
CSS でレイアウト制御しやすいのでオススメです。
<script type="text/javascript">
jQuery(document).ready( function() {
	jQuery( "#textsize a" ).textresizer({
		target: "#contents",
		type: "cssClass",
		sizes:	[
			"f1",
			"f2",
			"f3" 
				]
	});
});
</script>


type:”css”

type:"css" の場合、sizes には スタイルを直接書きます。
ベタ書きになるので個人的にはあまりオススメしません。
<script type="text/javascript">
jQuery(document).ready( function() {
	jQuery( "#textsize a" ).textresizer({
		target: "#contents",
		type: "css",
		sizes:	[
			{"font-size":"80%"},
			{"font-size":"100%"},
			{"font-size":"120%"}
				]
	});
});
</script>


HTML の記述例とサンプル

オプションで指定した target:"#contents" の範囲に対して文字サイズの変更が適用されます。
<div id"contents">
<ul id="textsize">
    <li><a href="javascript:void(0)" class="f1" >小</a></li>
    <li><a href="javascript:void(0)" class="f2" >中</a></li>
    <li><a href="javascript:void(0)" class="f3" >大</a></li>
<li>
</ul>

<p>文字が拡大されます。</p>

</div>

ごっつい簡単なデモも用意しています。
jQuery Text Resizer のデモ



  • このエントリーをはてなブックマークに追加
  • follow us in feedly

コメント

コメントを残す