重要なお知らせ

「教えて! goo」は2025年9月17日(水)をもちまして、サービスを終了いたします。詳細はこちら>

電子書籍の厳選無料作品が豊富!

下記のようにテストサイトを作ってみたのですが、<div class="im"><img ~></div>のimgにうまくclassがついてくれません。
ご教授の程宜しくお願いします。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>画像をぴったり合わせるテスト</title>
<style type="text/css">
.im {
position: relative;
width: 250px;
height: 250px;
overflow:hidden;
}
.vertically_long{
position: absolute;
top: -100%;
left: -100%;
right: -100%;
bottom: -100%;
width: 100%;
height: auto;
margin: auto;
}
.horizontally_long{
position: absolute;
top: -100%;
left: -100%;
right: -100%;
bottom: -100%;
width: auto;
height: 100%;
margin: auto;
}
.square{
position: absolute;
top: -100%;
left: -100%;
right: -100%;
bottom: -100%;
width: 100%;
height: auto;
}
</style>
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script>
(function(){
var imgW = $(".im img").width();
var imgH = $(".im img").height();

if(imgW>imgH || imgW==imgH){
$(".im img").addClass("horizontally_long");
} else if(imgW<imgH){
$(".im img").addClass("vertically_long");
} else {
$(".im img").addClass("square");
}
});
</script>

</head>
<body>
<div class="im"><img src="images/image01.jpg" width="1920" height="1280" alt=""></div>
</body>
</html>

A 回答 (1件)

見た感じクラスはつくと思いますが・・・



<script>
$(function(){
var imgW = $(".im img").width();
var imgH = $(".im img").height();
$(".im img")
.toggleClass("horizontally_long",imgW>imgH)
.toggleClass("vertically_long",imgW<imgH)
.toggleClass("square",(imgW==imgH));
});
</script>
    • good
    • 0
この回答へのお礼

早々にありがとうございます。
来週月曜日に試させて頂きます。

お礼日時:2017/02/10 17:51

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!