【问题标题】:Getting picture's width or height with js?! I need that for centering a picture width height: auto用js获取图片的宽度或高度?!我需要它来居中图片宽度高度:自动
【发布时间】:2018-05-26 17:43:31
【问题描述】:

我真的不知道这有什么问题......哈哈

我正在尝试这样做,它非常重要...你能帮帮我吗?

会很好: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


【解决方案1】:

你的变量“img”没有任何属性或方法,如高度或宽度,你需要从窗口对象中获取 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);

【讨论】:

    【解决方案2】:

    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>

    【讨论】:

      猜你喜欢
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多