javascript - 如何以百分比形式接收图像的值

标签 javascript jquery

我有 2 个图像和一个输入类型编号。单击输入字段的值并更改为图像的百分比宽度时是否可能,因为现在它只需要像素。在示例中,我编写了一个简单的 2 个图像和一个输入字段的脚本。

$("img").on('click', function() {
  var widthI = $(this).css("width").replace(/[^-\d\.]/g, ''); //become pixels need the value of the width i gave with it.
  console.log(widthI + " percentage");
  $("#widthI").val(widthI);

  console.log(widthI);
});
#img1 {
  width: 12.5%
}

#img2 {
  width: 25%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://pbs.twimg.com/profile_images/955031454781616129/JRpZOp1l_400x400.jpg" id="img1" />
<br>
<img src="https://gupta-strategists.nl/storage/images/team/_teamImage/JK_Gupta_Eigen_fotos_2000_011-2.jpg" id="img2" />
<br>
<input type="number" id="widthI" />

我还做了一个Codepen

最佳答案

由于图像将根据其父级尺寸调整大小,因此您可以执行以下操作:

$( "img" ).on('click', function() {
    var imgWidth = $(this).width();
    var parentWidth = $(this).parent().width();

    // Round values to get only two decimals (e.g. 12.3333339% will be rounded to 12.34%)
    var imageRatio = Math.round(imgWidth / parentWidth * 10000) / 100;

    console.log(imageRatio + "%");
});

关于javascript - 如何以百分比形式接收图像的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53171016/

相关文章:

javascript - 如何在jquery中添加一个或多个克隆

javascript - 在 vue js 中使用 mapActions 的确切目的是什么?

javascript - SHOPIFY 页面中 slider 下方的 Flexslider 缩略图(不是产品图片)

jquery - 移动数据输入 - 移动友好的数据网格

javascript - jquery 日期选择器 : weird documentation substraction in minDate

javascript - 如何修复 Vue 警告 : You may have an infinite update loop in a component render function

javascript - 如何在wordpress cms中使用css从div中删除属性

javascript 幻灯片增长更快,为什么?

javascript - 单击删除按钮时删除了所有项目以及如何使用 React.js 实现编辑/更新功能

jquery - MVC 4.5 异步 Ajax 调用不起作用