jQuery: 複数画像の幅を判定し個別のクラス名を追加

コンテンツ内の複数画像の幅を測定し、3段階のサイズに分類して、それぞれに該当するクラス名を付けたいということでjQueryを使用。

今回は、jQueryの「.each()」を使用。
以下デモでは、画像の変わりに「div」を使い、それぞれの幅サイズを「.width()」で測ってif文で分岐して各サイズのCSSを「.addClass()」を使って追加。
参考に「.before()」と「.after()」で取得した幅サイズとクラス名を書き出しています。

//jQuery

$(function(){
	$('div').each(function(){
		$w = $(this).width();
		$(this).before('width = '+$w);
		if($w<100){
			$w='size-s';
		}else if(100<$w && $w<150){
			$w='size-m';
		}else{
			$w='size-l';
		}
		$(this).after('class = '+$w).addClass($w);
	});
});

See the Pen xJwerz by nwstcode (@nwst) on CodePen.12804

tagTimeLog Lite

Simple time tracking tool
Developed by Namu Works