html5中是否支持createElement()?

时间:2013-12-03 21:17:29

标签: javascript css html5 browser doctype

在编写HTML5页面(包括PHP)时,我注意到当doctype切换到html5时,createElement()停止工作

<!DOCTYPE html>

代码是使用Javascript创建非常标准的元素:

function Rhit(){
        var Hit=document.createElement('div');
        if(Hit){
            alert('Hit assigned.');
            Hit.setAttribute('id','Hits');
            if(document.body.appendChild(Hit)){
                alert('Hit transferred to body; setting styles.');
                Hit.style.width='400';
                Hit.style.height='400';
                Hit.style.position='absolute';
                Hit.style.right='0';
                Hit.style.top='0';
                Hit.style.backgroundColor='#777777';
            }
        }
        else{
            alert('Create Element Error, please debug.');
        }

    }

(我在html5 doc类型下调试了一下......等等。) 弹出警报,但在html5 doctype下没有绘制div标签。 (使用常规html超级沙盒模式可以正常工作)

我错过了什么吗?

(此外,所有代码都显示在浏览器源代码中。)似乎代码正在解析但未绘制?

编辑:这是一个完整的演示。与此同时,我将这些评论添加到:

<html> <!--if !html5 document draws.-->
<head> 
 <script>
     function proc(){
        var foo=document.createElement('div');

        //Test foo creation.
        if(foo){
            alert('Hit assigned.'); 
            foo.setAttribute('id','Hits');

            //test foo location assignment.
            if(document.body.appendChild(foo)){

                alert('Hit transferred to body; setting styles.'); 

                //Set all other stuff.
                foo.style.width='400';
                foo.style.height='400';
                foo.style.position='absolute';
                foo.style.right='0';
                foo.style.top='0';
                foo.style.backgroundColor='#777777';
            }
        }
        //If failed, all is lost.
        else{
            alert('Create Element Error, please debug.');
        }

    }
 </script>
</head>
<title></title>
<body>
    <script>
    proc(); //Run function.
    document.write('Javascript Running...');
    //Failsafe (for IDE's who don't care if your eyes hurt and insist
    //that java has an error "somewhere".)
    </script>   
</body>

1 个答案:

答案 0 :(得分:7)

您的身高和宽度定义不正确,因此(iirc)被分配0

这些CSS样式规则要求值为百分比或像素。所以:

Hit.style.width = '400px';
Hit.style.height = '400px';

应该给元素一些尺寸,并让它被看到。