0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【jQuery】ブレイクポイントを設定してPC/SP画像を切り替える

Posted at

開始タグ

SP/PCで画像を使い分けたいけれど、それぞれソースを書くのはなんだかな・・・な時に使えるメモ。

方法

	$(window).on("load", function() {
		//----- PC/SP画像置換----- //

		// 置換の対象とするclass属性。
		var $elem = $(".image_switch");
		// 置換の対象とするsrc属性の文字列。
		var sp = "_sp";
		var pc = "_pc";
		// ウィンドウサイズがreplaceWidth以上、もしくは未満の場合に処理が発生する。
		var replaceWidth = breakpoint;

		$elem.each(function() {
			var $this = $(this);

			function imageSwitch() {
				var windowWidth = parseInt($(window).width());

				if (windowWidth > replaceWidth) {
					$this.attr("src", $this.attr("src").replace(sp, pc));
				} else if (windowWidth <= replaceWidth) {
					$this.attr("src", $this.attr("src").replace(pc, sp));
				}
			}
			imageSwitch();

			// 動的なリサイズは操作後0秒経ってから処理を実行する。
			var resizeTimer;
			$(window).on("load resize", function() {
				clearTimeout(resizeTimer);
				resizeTimer = setTimeout(function() {
					imageSwitch();
				}, 0);
			});
		});
	});

.image_switchを画像に与えてあげると、ブレイクポイントで判断して画像名の_pc``_spを置き換えてくれることで切り替えすることができます。

閉じタグ

これ見つけた当時「これー!」って声が出た覚えがあります。笑

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?