如果得到一个对象的属性是否已经设置?

<img src='XXX' width='100' /> 已经设置了 width 属性

<img src='XXX' /> 未设置 width 属性。

image.width 这个方法行不通,因为一样可以读出 width 的值。

解决方案 »

  1.   

    <img id="img01" src='XXX' width='100' /> <script type="text/javascript" language="javascript">
    function getWidth(imgID)
    {
    //获取width
    if (imgID=="") return;
    var o=document.getElementById(imgID);
    if (o.width != null)
        alert("image width = "+o.width);
    }
    function setWidth(imgID,nWidth)
    {
    //设置width
    if (imgID=="" || nWidth=="") return;
    var o=document.getElementById(imgID);
    o.width=parseInt(nWidth);
    }

    </script><input name="get width" type="button" onclick="javascript:getWidth('img01');">
    <input name="set width" type="button" onclick="javascript:getWidth('img01',200);">
      

  2.   

    不設置width默認是img的寬
    可以img.outerHTML.search("width")來判斷,-1表示沒有設置width
      

  3.   

    用搜索 width= 的方法也不是很行得通啊
    因为 src="xxx"
    xxx 中就可能含有 width= 这个字符串
      

  4.   

    簡單查找的話search(/\s+width=/)就可以了
      

  5.   

    不知道lz要干吗?得到width属性没有设置,然后重新设置?img元素默认都会取图片的大小的。
      

  6.   

    因为要把图片的 HTML 转为 UBB
    如果没定义宽和高,UBB就是 
    如果已定义宽和高,UBB 就是 
      

  7.   

    因为要把图片的 HTML 转为 UBB 
    如果没定义宽和高,UBB就是 [ img ]xxx[ /img ] 
    如果已定义宽和高,UBB 就是[ img=400,300 ]xxx[ /img ]
      

  8.   

    兼容:firefox 和 ie
    <img id="img1" width="10px" src="http://avatar.profile.csdn.net/5/2/B/2_faisun.jpg"/>
    <img id="img2" src="http://avatar.profile.csdn.net/5/2/B/2_faisun.jpg"/>
    <script type="text/javascript">
    var img1 = document.getElementById("img1");
    var img2 = document.getElementById("img2");
    alert((img1.attributes["width"] && img1.attributes["width"].specified) + "," + (img2.attributes["width"] && img2.attributes["width"].specified));
    </script>判断是就用
    if (img1.attributes["width"] && img1.attributes["width"].specified) {
        // todo
    }