“Node.insertBefore不是对象”错误

时间:2016-05-27 19:59:32

标签: javascript html

我是JavaScript的新手。我按照this tutorial创建了我的第一个项目,这是一个非常简单的图片幻灯片。这是我的完整代码:

<!DOCTYPE html>
<html>
<head>
  <title>Dummy Slideshow</title>
</head>
<body>
<style>
.fadein { position:relative; height:332px; width:500px;}
.fadein img { position:absolute; left:0; top:0; transition:opacity 1s; opacity:1; }
.fadein img.is-hidden { opacity:0; }
</style>
<div class="fadein">
  <img src="http://farm3.static.flickr.com/2610/4148988872_990b6da667.jpg">
  <img src="http://farm3.static.flickr.com/2597/4121218611_040cd7b3f2.jpg">
  <img src="http://farm3.static.flickr.com/2531/4121218751_ac8bf49d5d.jpg">
</div>
<script>
  var root = document.querySelector('.fadein');
  var els = root.querySelectorAll(':not(:first-child)');
  for (i=0; i < els.length; i++) {
    els[i].classList.add('is-hidden');
  }
  root.addEventListener('transitionend', function(){
    root.insertBefore(root.querySelector(':first-child.is-hidden'), null);
  });
  setInterval(function(){
    root.querySelector(':first-child').classList.add('is-hidden');
    root.querySelector(':nth-child(2)').classList.remove('is-hidden');
  }, 3000)
</script>
</body>
</html>

一开始一切都很顺利,直到我尝试激活firebug时,它显示错误:

TypeError: Argument 1 of Node.insertBefore is not an object.

错误引用了这一部分:

root.addEventListener('transitionend', function(){
   root.insertBefore(root.querySelector(':first-child.is-hidden'), null);
});

我也尝试将:first-child.is-hidden替换为.is-hidden:nth-of-type(1),但仍会出现错误。当我删除:first-child时,错误会以某种方式消失,但它会使幻灯片无法显示所有图片。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

transitionend事件被触发两次。一个加完后('is-hidden');删除后('is-hidden')。第二次':first-child.is-hidden'元素为空

var root = document.querySelector('.fadein');
var els = root.querySelectorAll(':not(:first-child)');
for (i = 0; i < els.length; i++) {
  els[i].classList.add('is-hidden');
}

root.addEventListener('transitionend', function() {
  if(root.querySelector(':first-child.is-hidden'))
  root.insertBefore(root.querySelector(':first-child.is-hidden'), null);
});
setInterval(function() {
  root.querySelector(':first-child').classList.add('is-hidden');
 root.querySelector(':nth-child(2)').classList.remove('is-hidden');
}, 3000)
 .fadein {
   position: relative;
   height: 332px;
   width: 500px;
 }
 .fadein img {
   position: absolute;
   left: 0;
   top: 0;
   transition: opacity 1s;
   opacity: 1;
 }
 .fadein img.is-hidden {
   opacity: 0;
 }
<body>

  <div class="fadein">
    <img src="http://farm3.static.flickr.com/2610/4148988872_990b6da667.jpg">
    <img src="http://farm3.static.flickr.com/2597/4121218611_040cd7b3f2.jpg">
    <img src="http://farm3.static.flickr.com/2531/4121218751_ac8bf49d5d.jpg">
  </div>

</body>