【发布时间】:2017-04-09 06:01:03
【问题描述】:
我正在拼凑一些脚本来在我的页面上创建浮云。
- 当我尝试调用 movechip() 函数时出现问题。
- 在调用该函数之前(在 for 循环中或在构造云的函数中)div 和图像被附加到容器 div 并且对象包含正确的属性(使用开发人员工具中的元素检查器进行验证)
- 我尝试将 movechip() 调用从构造函数移到 for 循环,但没有帮助
- 我删除了原始样式(使用 css)并使用 javascript 附加了样式。这也没有帮助。
使用脚本使用的完整说明(可以在这篇文章的底部找到)我制作了一个函数,它制作一个图像元素,将其附加到 div,将 div 附加到页面并调用“芯片”构造函数。我在 for 循环中调用该函数以获取页面上我想要的云数。
这里是for循环:
for ( var i = 0; i <= cloudNo/4; i ++ ) {
// call a function which creates a new div and chip object
var cloudName = "flyingCloud" + i.toString();
newCloud(i);
movechip(cloudName);
}
函数如下:
// cloud function
function newCloud(number) {
// assign a 'name' to the cloud to be used as the id and then passed to the chip function
var cloudName = "flyingCloud" + number.toString();
// create a div element to house the image
var cloud = document.createElement('div');
// create an image element
var cloudImg = document.createElement('img');
// append the image to the div
cloud.appendChild(cloudImg);
// assign image src as cloud url
cloudImg.src = cloudImageUrl;
// assign the cloudname as the ID
cloud.id = cloudName;
// set the style of the cloud div
cloud.setAttribute('style', 'position:absolute; left: -500px; width:50; height:62; font-size:10px;');
// append the cloud to the container div
cloudDiv.appendChild(cloud);
// create a new chip
cloud = new Chip(cloudName, 362,362);
}
但我不断收到此错误: moveobj.js:71 Uncaught TypeError: Cannot read property 'style' of null(...)
这是问题代码的链接,第 71 行正在尝试访问“芯片”的样式属性: http://samisite.com/extras/HTMLobj-1640/moveobj.js
我意识到这可能是一个非常容易解决的问题,但似乎无法找出问题所在。如果有任何意见,我将不胜感激。
完整的说明可以在这里找到:http://dynamicdrive.com/dynamicindex4/flyimage.htm
【问题讨论】:
-
我不认为你可以一次做多种风格,一次尝试一种?
-
我检查了控制台,它们的样式属性肯定在命名属性(
CSSStyleDeclaration 0:"position"1:"left"2:"width"3:"height"4:"font-size")上。我更改了单独添加它们只是为了看看它是否有任何区别并且只有一个属性成功附加(最后一个)。 -
document.getElementById(chip.named)为空,因为movechip中的chip没有属性named,它只是一个普通的div。 -
由于脚本需要全局变量,您可以在
newCloud的最后一行以window[ cloudName ] = new Chip(cloudName, 362,362);开头。这会让你克服这个特殊的错误,但老实说,这个脚本已经有十多年的历史了,按照今天的标准来说相当糟糕,所以我发现进一步的调试和修复毫无意义。这种飞行元素的效果根本不需要 JavaScript 就可以完成。
标签: javascript html css null