Javascript/自作jqueryライブラリ/画像正方形トリム
提供: 初心者エンジニアの簡易メモ
- trimsquare.js
$(function() {
jQuery.event.add(window, "load", function(){
var body_w = $(window).width(); // window width
var fw = body_w / 3; //fixed width
var fh = body_w / 3; //fixed height
$(".trim_square").css("width",fw+"px");
$(".trim_square").css("height",fw+"px");
var sl = '.trim_square img'; //selector
$(sl).each(function(){
var w = $(this).width();
var h = $(this).height();
if (w >= h) {
$(this).height(fh);
var iw = ($(this).width() -fw) / 2;
$(this).css("left", "-"+iw+"px");
$(this).css("top", "0px");
} else {
$(this).width(fw);
var ih = ($(this).height() - fh) / 2;
//$(this).css("top", "-"+ih+"px"); // middle合わせ
$(this).css("top", "0px"); // top合わせ
$(this).css("left", "0px");
}
// 表示
$(this).css("display", "inline");
});
});
});
/*
これだと端末幅が取得できない場合があるのでレイアウトが崩れる
$(function() {
$(".trim_square img").on('load', function() {
var body_w = $(window).width(); // window width
var fw = body_w / 4; //fixed width
var fh = body_w / 4; //fixed height
$(this).parent().parent().css("width",fw+"px");
$(this).parent().parent().css("height",fw+"px");
var w = $(this).width();
var h = $(this).height();
if (w >= h) {
$(this).height(fh);
var iw = ($(this).width() -fw) / 2;
$(this).css("left", "-"+iw+"px");
$(this).css("top", "0px");
} else {
$(this).width(fw);
var ih = ($(this).height() - fh) / 2;
//$(this).css("top", "-"+ih+"px"); // middle合わせ
$(this).css("top", "0px"); // top合わせ
$(this).css("left", "0px");
}
// 表示
$(this).css("display", "inline");
});
})
*/
- trimsquare.css
.trim_square img {
display:none; /*サイズ変更前は非表示*/
position:absolute;
}
.trim_square {
position:relative;
overflow:hidden;
}
- sample.html
<div class="trim_square"> <img src="test.png" /> </div> <div class="trim_square"> <img src="test.png" /> </div>
