removeChild仅适用于img

时间:2016-11-08 16:47:13

标签: javascript

我想在点击和图像时删除叠加层,但它没有。 当我点击div(叠加)时,叠加层消失,但是当我点击照片时,叠加层没有消失。控制台没有显示错误。

(function (){
    
  

    window.onclick=function (e){
    
    var hit=e.target.tagName;
    

    if(hit=='IMG'){
    
    overlay=document.createElement('div');
    overlay.id='photo';
    document.body.appendChild(overlay);
    overlay.style.position='absolute';
    overlay.style.top=0;
    overlay.style.background='rgba(0,0,0,0.53)';
    overlay.style.cursor='pointer';
    overlay.style.width=window.innerWidth+"px";
    overlay.style.height=window.innerHeight+"px";
    
    
    photo=e.target.src;
    popeikona=document.createElement('IMG');
    popeikona.src=photo;
    overlay.appendChild(popeikona);
    popeikona.style.width='550px';
    popeikona.style.height='380px';
    
    popeikona.style.margin='15%';
    
    
    
   }; 
   
        
        overlay.addEventListener('click',function (){
        
        overlay.parentElement.removeChild(overlay);
        
    });
        

    
     window.onscroll=function (){
         
         if(overlay){
         overlay.style.top=window.pageYOffset+"px";
         overlay.style.left=window.pageXOffset+"px";
     }
     };
     
  console.log(overlay);  
}



}());

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

创建新的叠加元素时,它没有附加任何侦听器。尝试:

    window.onclick=function (e){

        var hit=e.target.tagName;


        if(hit=='IMG'){

        overlay=document.createElement('div');
        overlay.id='photo';
        document.body.appendChild(overlay);
        overlay.style.position='absolute';
        overlay.style.top=0;
        overlay.style.background='rgba(0,0,0,0.53)';
        overlay.style.cursor='pointer';
        overlay.style.width=window.innerWidth+"px";
        overlay.style.height=window.innerHeight+"px";

        overlay.addEventListener('click',function (){        
          overlay.parentElement.removeChild(overlay);
        }        

        photo=e.target.src;
        popeikona=document.createElement('IMG');
        popeikona.src=photo;
        overlay.appendChild(popeikona);
        popeikona.style.width='550px';
        popeikona.style.height='380px';

        popeikona.style.margin='15%';       

        }
 };