求大神帮忙看一下,JS创建一个元素,然后获取这个元素的样式问题。。

我想要的效果是,创建一个元素LI,然后获取刚刚阶建这个元素样式表中的width ,我现在弄出来老是有错,但我又不知道为什么,求大神帮看看我到底哪里写错了,应该怎么改,谢谢哈。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <style>
            li{
                width: 300px;
                height: 20px;
                background: #002299;
                position: absolute;
                left: 0px;
            }
            div{
                width: 30px;
            }
        </style>
        <title></title>
        <script>
        
        function clsDiv(xd,classx){
                var xDi = document.createElement("li");
                xDi.className =" ";
                if(xd){
                    xDi.style.width =xd;
                    if(xDi.className == ""){
                        xDi.className = classx;
                    }
                    else{
                        xDi.className = classx + "sd";
                    }
                }
                return xDi;
            };
        
            function classNamex(DIVs,cel){
                if(window.getComputedStyle){
                    return parseFloat(DIVs.getComputedStyle(DIVs,null)[cel]);
                }
                else{
                    return parseFloat(DIVs.currentStyle[cel]);
                }
            };
            //
            
            //
            window.onload = function(){
                var  sdd = clsDiv("30px","sidw");
                console.log(sdd);
                console.log(sdd.style.width = classNamex(sdd,"width"));
                
            };
            
            
        </script>
    </head>
    <body>
    </body>
</html>
阅读 2.7k
2 个回答
DIVs.getComputedStyle(DIVs,null)[cel]//这里错了吧
window.getComputedStyle(DIVs,null)[cel]//这样才对
//另外你新建的元素是没有渲染的,应该是取不到值得,在这之前appendChild到body上应该就可以了

style方法是获取不到外部声明的样式的。只能获取到行内声明的样式。

例如 <li style="width:200px"></li>这种。

所以获取样式的话需要用getComputedStyle方法。

语法如下:

var style = window.getComputedStyle("元素", "伪类");

一般没有伪类的话,就直接window.getComputedStyle("元素",null)。

你用法写错了

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