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

标签 javascript jquery html css

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

请解决我的脚本问题

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';

}
<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>

最佳答案

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

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/

关于javascript - 如何在 if 条件下使用实际图像更改图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38025898/

相关文章:

javascript - anchor 内的 Div,停止重定向

javascript - jQuery .each() 函数通过索引访问其他选择器

jquery - 无法获得嵌套的 jquery 选项卡

javascript - 鼠标 :over event fires twice in Fabric. js

javascript - 在 JavaScript 中添加 Web 辅助功能支持

javascript - 如何在 Google map 上突出显示下拉所选区域的区域

jquery - 使用 css 转换和 jquery 创建一个三 Angular 形 div

javascript - 在 iOS 应用程序中嵌入 JavaScript 引擎

javascript - 如何使出现在点击上的文本对 SEO 可见?

javascript - 如果子div为空则隐藏父div