我有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
答案 0 :(得分:1)
由于图像将根据其父尺寸进行调整,因此您可以执行以下操作:
$( "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 + "%");
});