【问题标题】:Is this behaviour, unique to chrome, odd or the proper outcome?这种行为是 chrome 独有的,是奇怪的还是正确的结果?
【发布时间】:2011-02-15 01:23:54
【问题描述】:

发现一个涉及 jquery 和 chrome 的怪事。如果周围 div 的显示设置为“无”,则 img 元素的 attr('width') 似乎返回 0。不过,这在 Firefox 和 Opera 中运行良好。

那么,这是一个错误还是 chrome 断言了正确的 jquery 行为?

这是一个例子:

<html>
<head>
<script type="text/javascript" src="../jquery-1.4.min.js"></script>
<script type="text/javascript" src="return.js"></script>
</head>

<body>

<div class="foot">
  <img src="images/ref.png" width="500px" height="500px"  />
  <img src="images/ref1.png" width="300px" height="300px"  />
</div>

</body>
</html>

$(document).ready(function(){

$('div.foot').css('display','none');

var imageWidth = $('div.foot img').eq(0).attr('width');

alert(imageWidth); // returns 0 in chrome.

});

【问题讨论】:

    标签: jquery google-chrome attr


    【解决方案1】:

    我认为这可能是一个 Chrome 错误。

    首先,我如上所述运行了您的代码。如您所述,它显示为“0”。

    然后,我玩弄了上面的代码,并且能够使用以下代码在开发控制台中显示宽度(500):

    $('div.foot img').eq(0).attr('width');
    

    因此,我将您必须的原始代码重新编写为稍微小一点的代码。这按预期显示“500”:

    $(document).ready(function(){
        $('div.foot').css('display','none');
        alert($('div.foot img').eq(0).attr('width'));
    });
    

    在那之后,我能够运行您的原始代码并让它警报“500”。

    $(document).ready(function(){
        $('div.foot').css('display','none');
        var imageWidth = $('div.foot img').eq(0).attr('width');
        alert(imageWidth); // returns 0 in chrome.
    });
    

    简短回答:我很确定这是一个错误,因为它的行为不稳定。

    注意:我用 jQuery 1.4.4 试过这个。

    【讨论】:

      【解决方案2】:

      图像显示为inline,并且在隐藏父级时不提供宽度/高度(在 Chrome 中)。

      将您的图像设置为display:block;,Chrome 将为您提供宽度/高度。检查这个:http://jsfiddle.net/c4jdv/

      【讨论】:

        猜你喜欢
        • 2023-02-02
        • 1970-01-01
        • 2012-01-05
        • 1970-01-01
        • 2021-06-01
        • 1970-01-01
        • 2011-09-30
        • 1970-01-01
        • 2017-03-30
        相关资源
        最近更新 更多