Firefoxだと、
<img src="a.png" style="max-width:100; max-height:50;">
とすれば所望のことができるのですが、ie6のようにこの記述をサポートしていないブラウザでは、どのようにすればよろしいですか?
たとえば、Javascriptと組合せることでできますか?
JavaScript で作ってみました。
<html> <head> <script type="text/javascript"> max_width = 100 ; max_height = 50 ; function keep_max() { for (i in document.images) { if (document.images[i].width > document.images[i].height & document.images[i].width > max_width) { document.images[i].width = max_width ; } else { if (document.images[i].height > max_height) { document.images[i].height = max_height ; } } } } </script> </head> <body onload="keep_max()"> <img src="./1.jpg" /> <img src="./2.jpg" /> <img src="./3.jpg" /> <img src="./4.jpg" /> </body> </html>
ただしこれだとすべての画像に適用されるので、
特定の画像だけリサイズする場合は
<html> <head> <script type="text/javascript"> max_width = 100 ; max_height = 50 ; function keep_max() { for (i in document.images) { if (document.images[i].className != 'gazou_type') continue ; // gazou_type は適当に変更してください if (document.images[i].width > document.images[i].height & document.images[i].width > max_width) { document.images[i].width = max_width ; } else { if (document.images[i].height > max_height) { document.images[i].height = max_height ; } } } } </script> </head> <body onload="keep_max()"> <img src="./1.jpg" /> <img src="./2.jpg" class="gazou_type" /> 変更対象の画像に class名を付ける <img src="./3.jpg" class="gazou_type" /> <img src="./4.jpg" /> </body> </html>
こんな感じ。
<img>タグでは、WIDTH属性(横幅指定)とHEIGHT属性(縦幅指定)が指定できるはずですが、それでもダメでしょうか?
http://www.htmq.com/html/img.shtml
もっとも縦横比固定は自分で計算しないとダメですが。
"縦横比を固定したまま"がポイントです。
の中でWIDTH属性とHEIGHT属性を両方とも指定すると、縦横比が崩れてしまいます。
JavaScript で作ってみました。
<html> <head> <script type="text/javascript"> max_width = 100 ; max_height = 50 ; function keep_max() { for (i in document.images) { if (document.images[i].width > document.images[i].height & document.images[i].width > max_width) { document.images[i].width = max_width ; } else { if (document.images[i].height > max_height) { document.images[i].height = max_height ; } } } } </script> </head> <body onload="keep_max()"> <img src="./1.jpg" /> <img src="./2.jpg" /> <img src="./3.jpg" /> <img src="./4.jpg" /> </body> </html>
ただしこれだとすべての画像に適用されるので、
特定の画像だけリサイズする場合は
<html> <head> <script type="text/javascript"> max_width = 100 ; max_height = 50 ; function keep_max() { for (i in document.images) { if (document.images[i].className != 'gazou_type') continue ; // gazou_type は適当に変更してください if (document.images[i].width > document.images[i].height & document.images[i].width > max_width) { document.images[i].width = max_width ; } else { if (document.images[i].height > max_height) { document.images[i].height = max_height ; } } } } </script> </head> <body onload="keep_max()"> <img src="./1.jpg" /> <img src="./2.jpg" class="gazou_type" /> 変更対象の画像に class名を付ける <img src="./3.jpg" class="gazou_type" /> <img src="./4.jpg" /> </body> </html>
こんな感じ。
ieでも縦横比を維持したまま画像を縮小することができました。
ありがとうございました。
ieでも縦横比を維持したまま画像を縮小することができました。
ありがとうございました。