代码之家  ›  专栏  ›  技术社区  ›  Omar Abid

在Internet Explorer中获取图像的宽度和高度

  •  1
  • Omar Abid  · 技术社区  · 15 年前

    <div id="wrapper">
    ...
    <img src="myphoto.png" height="400px" width="500px>
    </div>
    

    我使用jQuery来访问我使用的高度或宽度

    jQuery(img).attr('height');
    

    jQuery(img)[0].height;
    

    例如,如果我这样做了

    $('#wrapper').hide()
    then
    jQuery(img)[0].height = 0;
    

    属性也一样。

    任何关于如何解决这个问题的想法,显示DIV,获取值并再次隐藏它都可以解决问题,但是我无法猜测包装DIV的数量(它们的行为也会改变)。

    编辑: 谢谢你的回答。但是,我忘了提到我不控制DIV隐藏和样式。我的脚本可以播放图像,并且可以集成到任何页面中,因此用户就是隐藏/显示/更改值的人。

    4 回复  |  直到 15 年前
        1
  •  6
  •   Nick Craver    15 年前

    使用 .css() 获取存储值,如下所示:

    jQuery('img').css('height');
    

    我知道这听起来有点奇怪, but before you dismiss it, try it :)

        2
  •  0
  •   Pim Jager    15 年前

    var dimensions = {width: $(img).width(), height: $(img).height()};
    $(img).hide();
    

    或者,当由于隐藏和对值的需要分散开来而无法执行此操作时,可以在数据对象中保存高度和宽度

    $(img).data('dimensions', {width: $(img).width(), height: $(img).height()});
    

    然后您可以这样访问它们:

     $(img).data('dimensions').width;
    

    您甚至可以使用以下代码确保页面上的所有图像都具有这些数据属性:

    $(document).ready(function(){
        $('img').each(function(){ //embedded images
            $this = $(this);
            $this.data('dimensions', {width: $this.width(), height: $this.height()});
        });
        $('img').live('load', function(){ //inserted images
            $this = $(this);
            $this.data('dimensions', {width: $this.width(), height: $this.height()});
        });
    });
    
        3
  •  0
  •   Community CDub    8 年前

    Convert css width string to regular number

    .hide() display: none )你可以把它藏起来 .css('visible', 'hidden') 然后 .width()/.height() 会有用的。

    如果你不想改变主意 .hide() 那你就可以申请了 visible: hidden .show() 然后测量高度。测量完后,把它倒过来。对象被隐藏时仍会影响页面布局 可见:隐藏 -当心这个。

        4
  •  0
  •   hosam ebrahim    12 年前
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <input type="file" id="file" />
    <script type="text/javascript" charset="utf-8">
    $("#file").change(function(e) {
        var file, img;
        file = document.getElementById("file");
        if (file!=null) {
            img = new Image();
            img.src = file.value;
            img.onload = function() {
                alert(img.width + " " + img.height);
            };
            img.onerror = function() {
                alert( "not a valid file: " + file.type);
            };
        }
    
    });
    </script>