Webページ内にある画像の横幅を400ピクセルにリサイズする JavaScript + jQuery のサンプル。
さまざまな大きさの画像を、
一括で同じ大きさの画像にリサイズする (縦横比そのままで)。
サンプルコード。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sample of Resizing Images</title>
<script src="http://www.nilab.info/lib/js/jquery/3.0.0/jquery-3.0.0.min.js"></script>
<script>
$(document).ready(function(){
var resizeElementWidth = function(element, width){
element.width(width);
};
var resizeImages = function(){
var resizeWidth = 400;
$("img").each(function(){
var img = $(this);
if(img.width() > resizeWidth){
resizeElementWidth(img, resizeWidth);
}
});
}
$("#resize-button").on("click", function(){
resizeImages();
});
});
</script>
</head>
<body>
<div>
<h1>Sample of Resizing Images</h1>
<button id="resize-button" type="button">Resize Images</button>
<p><img src="image800.jpg" style="margin: 20px; padding: 20px; border: solid 3px #000000;" /></p>
<p><img src="image600.jpg" style="margin: 10px; padding: 10px; border: solid 2px #000000;" /></p>
<p><img src="image400.jpg" style="margin: 5px; padding: 5px; border: solid 1px #000000;"/></p>
<p><img src="image200.jpg" style="margin: 0px; padding: 0px; border: solid 0px #000000;"/></p>
</div>
</body>
</html>
動作するサンプルはこちら
⇒ Sample of Resizing Images
画像を親の要素のサイズに合わせてくれる imgLiquid という jQuery のプラグインもあったけど、今回は用途が違うので見送り。
⇒ [ヅ] jQuery プラグイン imgLiquid: 画像を良い感じにリサイズしてくれる (2015-01-03)
tags: javascript jquery image
Posted by NI-Lab. (@nilab)