gpt4 book ai didi

javascript - html5 支持 createElement() 吗?

转载 作者:太空宇宙 更新时间:2023-11-04 14:18:04 24 4
gpt4 key购买 nike

在编写 HTML5 页面(包括 PHP)时,我注意到当文档类型切换为 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 文档类型下对其进行了一些调试......有点。)警报弹出,但在 html5 文档类型下没有绘制任何 div 标签。 (适用于常规 html super 沙箱模式)

我错过了什么吗?

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

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

<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>

最佳答案

您的高度和宽度定义不正确,因此 (iirc) 被指定为 0

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

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

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

关于javascript - html5 支持 createElement() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20361857/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com