如何在if条件下使用实际图像更改图像大小

时间:2016-06-25 06:58:20

标签: javascript jquery html css

脚本代码未运行我需要图像顶部和底部空间高于宽度1000px图像,低于宽度1000px图像然后在其他情况下获取宽度和高度条件

请解决我的脚本问题



var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style > 1000) { /*  image actual size above 1000px then set below height and width */
    yourImg.style.height = '200px';
    yourImg.style.top = '20px';
    yourImg.style.bottom = '20px';
    yourImg.style.width = '200px';
}
else if (yourImg && yourImg.style < 1000) /*  image actual size below  1000px then set below height and width */
{
  yourImg.style.height = '200px';
    yourImg.style.width = '200px';

}
&#13;
<div style="  border-right:1px solid #fff; "> 
 <a href="#">
 <img  class="img-responsive" alt="product" src="http://olpur.com/admin2/products/15201small.jpg" id="yourImgId" style=" width:100%;border:none;  object-fit: contain; object-position: top 75%;" />
                                            </a>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我认为您尝试使用yourImg.style来获取图像的当前宽度,而不是yourImg.clientWidth

var yourImg = document.getElementById('yourImgId');

if (yourImg && yourImg.clientWidth > 1000) {
  yourImg.style.height = '200px';
  yourImg.style.top = '20px';
  yourImg.style.bottom = '20px';
  yourImg.style.width = '200px';
}
else if (yourImg && yourImg.clientWidth < 1000) {
  yourImg.style.height = '200px';
  yourImg.style.width = '200px'; 
}

https://jsfiddle.net/a35u2fm9/