构造新对象时未捕获类型错误

时间:2016-11-24 21:32:15

标签: javascript html css null

我正在拼凑一些脚本来在我的页面上创建浮云。

  1. 当我尝试调用movechip()函数时出现问题。
  2. 在调用该函数之前(在for循环或构建云的函数中)div和图像被附加到容器div,并且对象包含正确的属性(使用开发人员工具中的元素检查器进行验证)
  3. 我尝试将movechip()调用从构造函数移动到for循环但是没有帮助
  4. 我删除了原始样式(使用css)并使用javascript附加了样式。这也没有帮助。
  5. 使用脚本使用的完整说明(可以在本文的底部找到)我创建了一个函数,它创建一个图像元素,将它附加到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:无法读取属性&#39; style&#39; of null(...)

    这里是问题代码的链接,第71行试图访问&#39;芯片的样式属性: http://samisite.com/extras/HTMLobj-1640/moveobj.js

    我意识到这可能是一个非常容易解决的问题,但似乎无法弄清楚错误是什么。我会非常感激任何意见。

    完整说明可在此处找到:http://dynamicdrive.com/dynamicindex4/flyimage.htm

1 个答案:

答案 0 :(得分:0)

setAttribute只会覆盖样式属性到最后一个!我不知道,所以我找到了另一个解决方案

Styling JS Dom object

cloud.style.position = "absolute";
cloud.style.left = "-500px";
cloud.style.width = "50px";
cloud.style.height = "62px";
cloud.style.fontSize = "10px";
相关问题