用js获取图片的宽度或高度?!我需要它来居中图片宽度高度:auto

问题描述 投票:-3回答:2

我真的不知道那是错的......哈哈

我试图这样做而且非常重要......你能帮助我吗?

会很好的:D

谢谢

<script>

var img = document.getElementById("img");

  var height = img.height;
  var width = img.width;

alert(height);

</script>

<div>

	<img id="img" src="https://www.w3schools.com/css/trolltunga.jpg">

</div>

<style>

#img {
position: absolute;
top: 50%;
left: 50%;
width: 400px;
height: auto;
margin-left: -200px;
}


</style>
javascript html css image
2个回答
0
投票

你变量“img”没有任何属性或方法,如高度或宽度,你需要从window对象获取computedStyle,如下所示:

var img = document.getElementById('img');

var height = window.getComputedStyle(img,null).getPropertyValue("height");
var width= window.getComputedStyle(img,null).getPropertyValue("width");

alert(height);
alert(width);

0
投票

js和jquery都有这个解决方案,我建议使用jquery作为更容易和更短的解决方案。它还可以使您的图像定位更容易。


var height = window.getComputedStyle(img,null).getPropertyValue("height");
var width= window.getComputedStyle(img,null).getPropertyValue("width");
jqHeight = $('#img').height();
jqWidth = $('#img').width();

$('.values').html('<p>Js method --> Height: '+height+' |  Width:'+width+'</p></br><p>Jquery method --> Height: '+jqHeight+' |  Width:'+jqWidth+'</p>');
#img {
position: absolute;
top: 50%;
left: 50%;
width: 400px;
height: auto;
margin-left: -200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div class="values"></div>

<div>
	<img id="img" src="https://www.w3schools.com/css/trolltunga.jpg">
</div>
© www.soinside.com 2019 - 2024. All rights reserved.