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

时间:2017-12-12 22:44:06

标签: javascript html css image

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

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

非常好:D

THX

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

2 个答案:

答案 0 :(得分:0)

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

.so

答案 1 :(得分: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>