jquery动态添加元素后,获取元素宽度与实际宽度不一致

代码如下

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Slideout Demo</title>
    <meta http-equiv="cleartype" content="on">
    <meta name="MobileOptimized" content="320">
    <meta name="HandheldFriendly" content="True">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <style>
        .product_list_con{
            text-align: center;
        }
        .product_list{
            display: inline-block;
        }
        .product_list li{
            display: inline-block;
        }
        .product_list li img{
            display: block;
        }
    </style>
    </head>
    <body>
        <div class="product_list_con">
            <ul id="product_list" class="product_list"></ul>
        </div>
        <script src="libs/jquery-3.1.1.min.js"></script>
        <script>
            var pros=[
              {imgSrc:"app/images/img_home/pro_1.jpg",imgAlt:"产品1",productName:'产品1'},
              {imgSrc:"app/images/img_home/pro_2.jpg",imgAlt:"产品1",productName:'产品1'},
              {imgSrc:"app/images/img_home/pro_3.jpg",imgAlt:"产品1",productName:'产品1'},
              {imgSrc:"app/images/img_home/pro_4.jpg",imgAlt:"产品1",productName:'产品1'},
              {imgSrc:"app/images/img_home/pro_5.jpg",imgAlt:"产品1",productName:'产品1'},
              {imgSrc:"app/images/img_home/pro_6.jpg",imgAlt:"产品1",productName:'产品1'},
              {imgSrc:"app/images/img_home/pro_7.jpg",imgAlt:"产品1",productName:'产品1'},
              {imgSrc:"app/images/img_home/pro_8.jpg",imgAlt:"产品1",productName:'产品1'}
            ];
            var html="";
            for(let i=0;i<pros.length;i++){
              html+=`<li>
                <img src=`+pros[i].imgSrc+` alt=`+pros[i].imgAlt+`>
                <spAn>`+pros[i].productName+`</span>
              </li>`
            }
            
            var oProductList=$("#product_list");
            oProductList.append(html);
            console.log($("#product_list li").width())
            console.log($("#product_list li"))
            console.log(document.getElementsByTagName("li")["0"].offsetWidth);
            // console.log(oProductList.children('li'));    
        </script>
    </body>
</html>

效果图:

clipboard.png
描述:
如代码所示,动态添加八个li到product_list 元素中,然后获取li的宽度,在谷歌浏览器中,元素审查实际宽度为如图所示:

clipboard.png

如图所示:

clipboard.png

依次为jquery打印元素li的宽度width、页面li元素、原生js打印offsetWidth;

检查元素的属性发现如下图所示:

clipboard.png

在这里看到offsetWidth和clientWidth都是56像素宽度,但是打印出的元素宽度却是41像素

百度不得其解,若你知道原因,请为我解惑,不胜感激!

阅读 6.4k
1 个回答

41是你图片还没加载出来的宽度,就是“产品一”文字的宽度
你应该给添加进来的img绑定onload事件,load以后再获取宽度

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题