Javascript/CSS灯箱仅适用于第一个元素? [英] Javascript/CSS Lightbox only working for first element?

查看:65
本文介绍了Javascript/CSS灯箱仅适用于第一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在单击每张照片时在Javascript/CSS灯箱中打开每张照片.

目前,我的照片列表中只有第一张照片在灯箱中打开.其他照片不会在灯箱中打开.

请有人可以解释/告诉我为什么这样做,并解释/告诉我这样做的正确方法吗?

这是我的HTML/PHP:

 <?php $ result4 = $ mysqli-> query("SELECT * FROM user_data WHERE user_id = $ p_id");if($ result4-> num_rows> 0){回声'< div class ="profile_gallery_image">< img id ="myImg" src ='.$ image.'.height ="100%" width ="100%"/></div>';回声'< div class ="profile_gallery_image">< img id ="myImg" src ='.$ image.'.height ="100%" width ="100%"/></div>';回声'< div class ="profile_gallery_image">< img id ="myImg" src ='.$ image.'.height ="100%" width ="100%"/></div>';回声'< div class ="profile_gallery_image">< img id ="myImg" src ='.$ image.'.height ="100%" width ="100%"/></div>';回声'< div class ="profile_gallery_image">< img id ="myImg" src ='.$ image.'.height ="100%" width ="100%"/></div>';回声'< div class ="profile_gallery_image">< img id ="myImg" src ='.$ image.'.height ="100%" width ="100%"/></div>';}?><!-模态->< div id ="myModal" class ="modal">< span class ="close"& times;</span>< img class ="modal-content" id ="img01"></div> 

CSS:

 < style>#myImg {光标:指针;过渡:0.3秒;}#myImg:hover {转换:scale(1.09);边框:1px实线#a5a5a5;}/*模态(背景)*/.modal {显示:无;/*默认隐藏*/位置:固定;/*留在原地*/z索引:10;/*坐在最上面*/padding-top:100像素;/*盒子的位置*/左:0;最高:0;宽度:100%;/* 全屏宽度 */高度:100%;/*全高*/溢出:自动;/*如果需要,启用滚动*/背景颜色:rgb(0,0,0);/*后备颜色*/背景颜色:rgba(0,0,0,0.9);/*黑色,不透明*/}/*模态内容(图像)*/.modal-content {保证金:自动;显示:块;宽度:100%;最大宽度:500像素;边框:1px实线#f1f1f1;border-radius:0px;}/*模态图像的标题*//*添加动画*/.modal-content,#caption {-webkit-animation-name:缩放;-webkit-animation-duration:0.6秒;animation-name:缩放;动画时间:0.6秒;}@ -webkit-keyframes zoom {来自{-webkit-transform:scale(0)}到{-webkit-transform:scale(1)}}@keyframes zoom {来自{transform:scale(0)}到{transform:scale(1)}}/*关闭按钮*/.关闭 {位置:绝对;顶部:15px;右:35px;颜色:#f1f1f1;font-size:40px;font-weight:粗体;过渡:0.3秒;}.close:悬停,.close:focus {颜色:#bbb;文字修饰:无;光标:指针;}/*在较小的屏幕上图像宽度为100%*/@仅限媒体屏幕和(最大宽度:700像素){.modal-content {宽度:100%;}}</style> 

JavaScript:

 < script>//获取模态var modal = document.getElementById('myModal');//获取图像并将其插入模态中-使用其"alt"文本作为标题var img = document.getElementById('myImg');var modalImg = document.getElementById("img01");img.onclick = function(){modal.style.display ="block";modalImg.src = this.src;}//获取< span>关闭模态的元素var span = document.getElementsByClassName("close")[0];var span2 = document.getElementsByClassName("modal")[0];//当用户点击< span>(x),关闭模态span.onclick = function(){modal.style.display ="none";}span2.onclick = function(){modal.style.display ="none";}</script> 

谢谢.

解决方案

纯Javascript灯箱/图片弹出模式

我希望分享一个完全符合节点.;href =">< img alt =""src =""/</a" .

  • 在网页上实施此Lightbox时,它的工作非常简单,例如,您点击触摸或在任意页面上的IMG标签的图片以及Modal或Lightbox将弹出,以显示相同的URL图像或存储在IMG标签的父A标签中的另一个URL图片.

    • 用于存储不同质量图像的相同或不同URL取决于您的选择.前者易于实现,而后者具有更好的性能.

  • 现在让我们看一些代码:


    这是包含图像和指向其他页面的URL的示例HTML .

     < a href ="https://1.bp.blogspot.com/-jNZtfo_qgNM/YHH_XF6FooI/AAAAAAAAC5E/y_tNUslqFPITSVncCkF3zyEC-RROSvETgCLcBGAsYHQ/s328/1.jpg"标题=第一图像"> <img alt =第一图像".src ="https://1.bp.blogspot.com/-jNZtfo_qgNM/YHH_XF6FooI/AAAAAAAAC5E/y_tNUslqFPITSVncCkF3zyEC-RROSvETgCLcBGAsYHQ/s320/1.jpg"/>/a>< a href ="https://1.bp.blogspot.com/-F0sshQGKu8Y/YHH_XL41aDI/AAAAAAAAC5M/fyAeo4X2tFw-RN-g8YFxNcel0WivQjj5gCLcBGAsYHQ/s400/2.jpg"标题=第二图像"> <img alt =第二图像".src ="https://1.bp.blogspot.com/-F0sshQGKu8Y/YHH_XL41aDI/AAAAAAAAC5M/fyAeo4X2tFw-RN-g8YFxNcel0WivQjj5gCLcBGAsYHQ/s320/2.jpg"/< a href =" https://1.bp.blogspot.com/-xk_pNZ1fh7o/YHH_XEROwmI/AAAAAAAAC5I/-WOsyfKgtSMRzXQBeEX-yjRX8TBJuEkFwCLcBGAsYHQ/s400/3.jpg标题=第三图像"> <img alt =第三图像".src =" https://1.bp.blogspot.com/-xk_pNZ1fh7o/YHH_XEROwmI/AAAAAAAAC5I/-WOsyfKgtSMRzXQBeEX-yjRX8TBJuEkFwCLcBGAsYHQ/s320/3.jpg"< a href =" https://1.bp.blogspot.com/-e3gjnYR7exE/YHH_YHRQgLI/AAAAAAAAC5Q/kgQYFsvBjuYPAXTjzMFkzvsRT6JgQlkywCLcBGAsYHQ/s720/4.jpg标题=第四图像"> <img alt =第四图像".src ="https://1.bp.blogspot.com/-e3gjnYR7exE/YHH_YHRQgLI/AAAAAAAAC5Q/kgQYFsvBjuYPAXTjzMFkzvsRT6JgQlkywCLcBGAsYHQ/s320/4.jpg"/< a href =" https://1.bp.blogspot.com/-zGPorKCAHqw/YHH_YHcIpSI/AAAAAAAAC5U/Jx2serYqk58fa_HSf1GPwDZu2nT1c8kJgCLcBGAsYHQ/s1280/5.jpg"标题=第五图像"> <img alt =第五图像".src ="https://1.bp.blogspot.com/-zGPorKCAHqw/YHH_YHcIpSI/AAAAAAAAC5U/Jx2serYqk58fa_HSf1GPwDZu2nT1c8kJgCLcBGAsYHQ/s320/5.jpg"/a>< a href =" https://anubhavyadavjovian.blogspot.com/> Anubhav yadav</a> 

    假设我们的网页上有五张图片,并且所有图片的格式为< a title ="href =">< img alt =""上面定义的src ="/"/.

    为显示此灯箱是动态的,我们添加了一个附加的< a href =" https://anubhavyadavjovian.blogspot.com/" Anubhav yadav</a> ,当按下,点击或Enter键时,其行为类似于正常A Href标签,而仅将IMG标签作为子级的A标签会弹出灯箱.


     < div id ='lightbox-home'>< div id ='lightbox-container'onclick ='hideoverlay()'>< img alt =''id ='lightbox-cont-img'onclick ='hideoverlay()'src =''/></div></div> 

    上面的 Real HTML 代码用于我们的灯箱,其中"lightbox-container" ID显示为半透明的黑色背景,带有带有"lightbox-cont-img" ID.


     #lightbox-container {z-index:2000;位置:固定;底部:-5000px;左:0px;宽度:100%;高度:100%;保证金:0px;background-color:rgba(38,38,38,0.85);过渡:所有0.4s缓解;显示:flex;flex-direction:column;证明内容:中心;align-items:center;}#lightbox-container.showcontainer {底部:0px;}#lightbox-container img {最大宽度:95%;最大高度:95%;对象适合:包含;}:重点 {边框:2px纯金;} 

    上面是 Real CSS ,用于装饰灯箱以及在出现和消失时创建过渡.


     //选择带有IMG子节点的所有A标签var atagswithimgtag = document.querySelectorAll("a [href]");//然后通过防止HREF打开新页面来防止A标签的默认行为//以及收集带有图像的A标签的所有HREF,以启用RIGHT和LEFT箭头键var allimgurlarray = [];for(i = 0; i< atagswithimgtag.length; i ++){var childAIMGtag = atagswithimgtag [i] .childNodes;if(childAIMGtag [0] .nodeType!= Node.TEXT_NODE)//或if(el [i] .nodeType!= 3){//这似乎也是一个带有IMG标签作为Childnode的A标签//首先,我们需要防止在新标签"中打开IMG的默认行为atagswithimgtag [i] .addEventListener("click",function(event){event.preventDefault();});//第二个是我们需要用A HREF填充图像URL的地方var listofnodes = atagswithimgtag [i];allimgurlarray [i] = [];allimgurlarray [i] [0] = i;allimgurlarray [i] [1] ="图像URL是;//listofnodes.getAttributeNode("title").value;allimgurlarray [i] [2] = listofnodes.getAttributeNode("href").value;}console.log(childAIMGtag [0] .innerHTML);}//现在我们必须处理键盘事件document.onkeydown =函数(事件){if(event.keyCode == 27){//如果按下ESC键if(document.getElementById("lightbox-container").classList.contains("showcontainer")){//LIGHTBOX ONdocument.getElementById("lightbox-container").classList.remove("showcontainer");}}否则if(event.keyCode == 13){//按下ENTER键if(document.getElementById("lightbox-container").classList.contains("showcontainer")){//LIGHTBOX ONdocument.getElementById("lightbox-container").classList.remove("showcontainer");}else {//灯箱关闭var currentEventTarget = document.activeElement;if(currentEventTarget.tagName =='A'){var entertargetchild = currentEventTarget.childNodes;if(entertargetchild [0] .tagName =='IMG'){var hrefofparent = currentEventTarget.getAttribute("href");document.getElementById("lightbox-cont-img").setAttribute("src",hrefofparent);document.getElementById("lightbox-container").classList.add("showcontainer");document.getElementById("lightbox-cont-img").focus();}}}}否则if(event.keyCode == 9){//按下TAB键if(document.getElementById("lightbox-container").classList.contains("showcontainer")){//LIGHTBOX ONdocument.getElementById("lightbox-container").classList.remove("showcontainer");}}else if(event.keyCode == 37){//左箭头键if(document.getElementById("lightbox-container").classList.contains("showcontainer")){//LIGHTBOX ON//首先获取显示在LIGHT BOX中的图像的URLvar currimgsrc = document.getElementById("lightbox-cont-img").getAttribute("src");//现在匹配数组中的序列号var serialofarray = 0;for(k = 0; k< allimgurlarray.length; k ++){if(currimgsrc == allimgurlarray [k] [2]){serialofarray = allimgurlarray [k] [0];}}//使用左箭头,我们应该减少序列,然后使用其ATTR SRC到LIGHT BOXif(serialofarray< = 0){serialofarray = allimgurlarray.length-1;}别的 {serialofarray = serialofarray-1;}console.log(左箭头:" + serialofarray);document.getElementById("lightbox-cont-img").setAttribute("src",allimgurlarray [serialofarray] [2]);}}否则if(event.keyCode == 39){//右箭头if(document.getElementById("lightbox-container").classList.contains("showcontainer")){//首先获取显示在LIGHT BOX中的图像的URLvar currimgsrc = document.getElementById("lightbox-cont-img").getAttribute("src");//现在匹配数组中的序列号var serialofarray = 0;for(l = 0; l< allimgurlarray.length; l ++){if(currimgsrc == allimgurlarray [l] [2]){serialofarray = allimgurlarray [l] [0];}}//使用向右箭头,我们应该增加序列,然后使用其ATTR SRC到LIGHT BOXif(serialofarray> = allimgurlarray.length-1){serialofarray = 0;}别的 {serialofarray = serialofarray +1;}console.log(右箭头:" + serialofarray);document.getElementById("lightbox-cont-img").setAttribute("src",allimgurlarray [serialofarray] [2]);}}else {//如果按下了ESC以外的任何其他键if(document.getElementById("lightbox-container").classList.contains("showcontainer")){document.getElementById("lightbox-container").classList.remove("showcontainer");}}}//通过此操作,我们正在处理CLICK ON IMAGE事件document.onclick =函数(事件){overlaypop(event);};函数overlaypop(event){如果(event === undefined)event = window.event;var targettag = event.target;var targetparent = event.target.parentNode;if(targettag.tagName =='IMG'){if(targetparent.nodeName =='A'){event.preventDefault();var hrefofparent = targetparent.getAttribute("href");//alert(单击'+ targettag.tagName +'父名称为'+ targetparent.nodeName +'且URL为'+ hrefofparent");document.getElementById("lightbox-cont-img").setAttribute("src",hrefofparent);document.getElementById("lightbox-container").classList.add("showcontainer");document.getElementById("lightbox-cont-img").focus();}}}函数hideoverlay(){document.getElementById('lightbox-container').classList.remove('showcontainer')} 

    使用上述Javascript,我们希望实现以下目的.

    1. 全屏显示的图片具有半透明的黑色背景,当触摸,单击或按下任何图像后使用TAB键导航到所需的图像.
    2. 触摸时隐藏此灯箱,在屏幕上的任意位置单击或按下键盘上的任何键(左箭头和右箭头键除外).
    3. 浏览以下格式的网页中的所有图像与左和右箭头键.

    简而言之,让我们通过了解Javascript的各个部分来了解此脚本如何实现我们的目的.

    1. 使用 document.querySelectorAll("a [href]"),我们希望获得所有IMG标签和父标签在名为 atagswithimgtag 的数组中的标签.

      • 我们将使用此数组,首先使用 event.preventDefault() 禁用在新页面中打开A标签的默认行为.
      • 然后,我们将使用此数组创建一个名为 allimgurlarray 的新2D数组,以存储A标签的HREF URL及其索引号.使用左右键时,这样可以实现更好的跟踪.
    2. 此后,我们必须处理两种类型的事件:即按键事件触摸/点击事件.

      • 按键事件是通过 document.onkeydown 处理的.在这里,我们必须在If-Else-If条件的帮助下处理 Enter,Tab,Esc,向右和向左箭头键.
      • 触摸或点击事件由 document.onclick 处理.
    3. 我们使用 .classList.contains 来检查Lightbox是隐藏的还是可见的.然后,我们分别使用 .classList.add .classList.remove 来显示和隐藏灯箱.

    4. 我们使用 document.activeElement .tagName .childNodes 来标识IMG标签及其父A标签,使用 TAB键进行导航后,按 Enter 键.

    5. 并且我们使用 window.event event.target event.target.parentNode .nodeName ,以在单击或触摸相应图像时标识IMG标签及其父A标签.

    6. 为使灯箱与ARIA更加兼容,我们使用 .focus()将焦点对准灯箱中当前显示的图像.


    单击,触摸或按任意键将在可见的情况下隐藏灯箱.


    检查此答案,以详细了解此Javascript如何处理诸如ESC 向左向右箭头.

    I am trying to open each of my photos in a Javascript/CSS lightbox upon each of the photos being clicked.

    At the moment, only the first photo in my list of photos is opening up in the lightbox. The other photos do not open in the lightbox.

    Please can someone explain/show me why this is and explain/show me the correct way of doing this?

    Here is my HTML/PHP:

    <?php $result4 = $mysqli->query("SELECT * FROM user_data WHERE user_id = $p_id");
        if($result4->num_rows > 0) {
        echo '<div class="profile_gallery_image"><img id="myImg" src='.$image.' height="100%" width="100%" /></div>';
        echo '<div class="profile_gallery_image"><img id="myImg" src='.$image.' height="100%" width="100%" /></div>';
        echo '<div class="profile_gallery_image"><img id="myImg" src='.$image.' height="100%" width="100%" /></div>';
        echo '<div class="profile_gallery_image"><img id="myImg" src='.$image.' height="100%" width="100%" /></div>';
        echo '<div class="profile_gallery_image"><img id="myImg" src='.$image.' height="100%" width="100%" /></div>';
        echo '<div class="profile_gallery_image"><img id="myImg" src='.$image.' height="100%" width="100%" /></div>';
    
        } ?>  
    
    <!-- The Modal -->
    <div id="myModal" class="modal">
      <span class="close">&times;</span>
      <img class="modal-content" id="img01">
    </div>
    

    CSS:

    <style>
    
    #myImg {
      cursor: pointer;
      transition: 0.3s;
    }
    
    #myImg:hover {
        transform: scale(1.09);
        border: 1px solid #a5a5a5;
    
    }
    
    /* The Modal (background) */
    .modal {
      display: none; /* Hidden by default */
      position: fixed; /* Stay in place */
      z-index: 10; /* Sit on top */
      padding-top: 100px; /* Location of the box */
      left: 0;
      top: 0;
      width: 100%; /* Full width */
      height: 100%; /* Full height */
      overflow: auto; /* Enable scroll if needed */
      background-color: rgb(0,0,0); /* Fallback color */
      background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
    }
    
    /* Modal Content (image) */
    .modal-content {
      margin: auto;
      display: block;
      width: 100%;
      max-width: 500px;
      border: 1px solid #f1f1f1;
      border-radius: 0px;
    
    }
    
    /* Caption of Modal Image */
    
    /* Add Animation */
    .modal-content, #caption {  
      -webkit-animation-name: zoom;
      -webkit-animation-duration: 0.6s;
      animation-name: zoom;
      animation-duration: 0.6s;
    }
    
    @-webkit-keyframes zoom {
      from {-webkit-transform:scale(0)} 
      to {-webkit-transform:scale(1)}
    }
    
    @keyframes zoom {
      from {transform:scale(0)} 
      to {transform:scale(1)}
    }
    
    /* The Close Button */
    .close {
      position: absolute;
      top: 15px;
      right: 35px;
      color: #f1f1f1;
      font-size: 40px;
      font-weight: bold;
      transition: 0.3s;
    }
    
    .close:hover,
    .close:focus {
      color: #bbb;
      text-decoration: none;
      cursor: pointer;
    }
    
    /* 100% Image Width on Smaller Screens */
    @media only screen and (max-width: 700px){
      .modal-content {
        width: 100%;
      }
    }
    </style>
    

    Javascript:

       <script>
    // Get the modal
    var modal = document.getElementById('myModal');
    
    // Get the image and insert it inside the modal - use its "alt" text as a caption
    var img = document.getElementById('myImg');
    var modalImg = document.getElementById("img01");
    img.onclick = function(){
      modal.style.display = "block";
      modalImg.src = this.src;
    
    }
    
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];
    var span2 = document.getElementsByClassName("modal")[0];
    
    // When the user clicks on <span> (x), close the modal
    span.onclick = function() { 
      modal.style.display = "none";
    }
    span2.onclick = function() { 
      modal.style.display = "none";
    }
    </script>
    

    Thanks in advance.

    解决方案

    Pure Javascript Lightbox / Image Popup Modal

    I wish to share a Pure Javascript Lightbox or Image Popup Modal which is completely compliant with the Navigation guidelines of ARIA and is lightweight and easy to implement because :

    1. It does not require any JQUERY hence an additional import request to CDN and the buffering of entire JQUERY library can be prevented.
    2. This is a deploy and forget kind of design where we only need to add the LIGHTBOX related HTML, CSS and JAVASCRIPT without any need to add unique IDs or CLASSes to the HTML tags of images or its parent A tag. That is why, later addition or removal of images from your exisitng webpages will not require any change in the Javascript or the ID/CLASS attributes of IMG/A tags.


    1. To implement this, a precursor is that all the images in IMG tag shall be the only Child node of a parent A tag like <a title="" href=""><img alt="" src=""/></a>.

      • Also, One thing to keep in mind is that there should be no White spaces in between opening and closing of A tag and IMG tag and it should appear as <a><img/></a>.

      • Since only IMG tag images are loaded when page is downloaded while A tags are not that is why creating a parent A tag for all the IMG tag allows to store smaller size of the images in IMG tag and larger size of the same images in the parent A tag.

      • Combining IMG tags with Loading="lazy" will help further speed up the page loading.

    2. This Lightbox is simple in working when implemented on a web page i.e. you Click, Touch or press Enter key on any image of IMG tag on page and a Modal or Lightbox will Popup to display the same URL image or a different one stored in the parent A tag of the IMG tag.

      • Same or Different URL for storing different quality images depend upon your choice. Former is easier to implement while later has a better performance.


    Now let us see some code :


    This a Sample HTML of A tags containing Images and URL to other pages.

    <a href="https://1.bp.blogspot.com/-jNZtfo_qgNM/YHH_XF6FooI/AAAAAAAAC5E/y_tNUslqFPITSVncCkF3zyEC-RROSvETgCLcBGAsYHQ/s328/1.jpg" title="first image"><img alt="first image" src="https://1.bp.blogspot.com/-jNZtfo_qgNM/YHH_XF6FooI/AAAAAAAAC5E/y_tNUslqFPITSVncCkF3zyEC-RROSvETgCLcBGAsYHQ/s320/1.jpg"/></a>
    
    <a href="https://1.bp.blogspot.com/-F0sshQGKu8Y/YHH_XL41aDI/AAAAAAAAC5M/fyAeo4X2tFw-RN-g8YFxNcel0WivQjj5gCLcBGAsYHQ/s400/2.jpg" title="second image"><img alt="second image" src="https://1.bp.blogspot.com/-F0sshQGKu8Y/YHH_XL41aDI/AAAAAAAAC5M/fyAeo4X2tFw-RN-g8YFxNcel0WivQjj5gCLcBGAsYHQ/s320/2.jpg"/></a>
    
    <a href="https://1.bp.blogspot.com/-xk_pNZ1fh7o/YHH_XEROwmI/AAAAAAAAC5I/-WOsyfKgtSMRzXQBeEX-yjRX8TBJuEkFwCLcBGAsYHQ/s400/3.jpg" title="third image"><img alt="third image" src="https://1.bp.blogspot.com/-xk_pNZ1fh7o/YHH_XEROwmI/AAAAAAAAC5I/-WOsyfKgtSMRzXQBeEX-yjRX8TBJuEkFwCLcBGAsYHQ/s320/3.jpg"/></a>
    
    <a href="https://1.bp.blogspot.com/-e3gjnYR7exE/YHH_YHRQgLI/AAAAAAAAC5Q/kgQYFsvBjuYPAXTjzMFkzvsRT6JgQlkywCLcBGAsYHQ/s720/4.jpg" title="fourth image"><img alt="fourth image" src="https://1.bp.blogspot.com/-e3gjnYR7exE/YHH_YHRQgLI/AAAAAAAAC5Q/kgQYFsvBjuYPAXTjzMFkzvsRT6JgQlkywCLcBGAsYHQ/s320/4.jpg"/></a>
    
    <a href="https://1.bp.blogspot.com/-zGPorKCAHqw/YHH_YHcIpSI/AAAAAAAAC5U/Jx2serYqk58fa_HSf1GPwDZu2nT1c8kJgCLcBGAsYHQ/s1280/5.jpg" title="fifth image"><img alt="fifth image" src="https://1.bp.blogspot.com/-zGPorKCAHqw/YHH_YHcIpSI/AAAAAAAAC5U/Jx2serYqk58fa_HSf1GPwDZu2nT1c8kJgCLcBGAsYHQ/s320/5.jpg"/></a>
    
    <a href="https://anubhavyadavjovian.blogspot.com/">Anubhav yadav</a>
    

    Let say we have five images on our webpage and all are in the format <a title="" href=""><img alt="" src=""/></a> as defined above.

    To show that this Lightbox is dynamic, we have included an additional <a href="https://anubhavyadavjovian.blogspot.com/">Anubhav yadav</a>, which will behave like a normal A Href Tag when Clicked, Touched or Enter key is pressed on it, while the A tags with only IMG tag as a Child will popup the Lightbox.


    <div id='lightbox-home'>
      <div id='lightbox-container' onclick='hideoverlay()'>
        <img alt='' id='lightbox-cont-img' onclick='hideoverlay()' src=''/>
      </div>
    </div>
    

    The Real HTML code above is for our Lightbox with a "lightbox-container" ID appearing as a translucent black background with an image displaying tag with "lightbox-cont-img" ID.


    #lightbox-container {
      z-index:2000;
      position:fixed;
      bottom:-5000px;
      left:0px;
      width:100%;
      height:100%;
      margin:0px;
      background-color: rgba(38, 38, 38, 0.85);
      transition: all 0.4s ease-out;
    
      display:flex;
      flex-direction:column;
      justify-content:center;
      align-items:center;
    }
    #lightbox-container.showcontainer {
      bottom:0px;
    }
    #lightbox-container img {
      max-width:95%;
      max-height:95%;
      object-fit:contain;
    }
    :focus {
      border: 2px solid gold;
    }
    

    Above is the Real CSS for the decoration of Lightbox as well as creating transitions while appearing and disappearing.


    // Select all A tags with IMG child nodes
    var atagswithimgtag = document.querySelectorAll("a[href]");
    
    // then prevent the default behaviour of A tags by preventing of opening new page by HREF
    // as well as collect all the HREF of A tags with images to enable RIGHT and LEFT arrow key
    var allimgurlarray = [];
    for(i=0;i<atagswithimgtag.length;i++){
      var childAIMGtag = atagswithimgtag[i].childNodes;
      if (childAIMGtag[0].nodeType != Node.TEXT_NODE) // or if (el[i].nodeType != 3)
      {
        // this seems too be a A tag with IMG tag as Childnode
    
        // first we need to prevent the default behaviour of opening the IMG in New Tab
        atagswithimgtag[i].addEventListener("click", function(event){
          event.preventDefault();
        });
    
        // second is when we need to fill image URL aray with A HREF
        var listofnodes = atagswithimgtag[i];
        allimgurlarray[i] = [];
        allimgurlarray[i][0] = i;
        allimgurlarray[i][1] = " Image URL is ";//listofnodes.getAttributeNode("title").value;
        allimgurlarray[i][2] = listofnodes.getAttributeNode("href").value;
      }
      console.log(childAIMGtag[0].innerHTML);
    }
    
    // now we have to deal with Keyboard events
    document.onkeydown = function(event){
      if(event.keyCode==27){ // If ESC key is pressed
        if(document.getElementById("lightbox-container").classList.contains("showcontainer")){ // LIGHTBOX ON
          document.getElementById("lightbox-container").classList.remove("showcontainer");
        }
      }
      else if(event.keyCode==13) { // ENTER key pressed
        if(document.getElementById("lightbox-container").classList.contains("showcontainer")){ // LIGHTBOX ON
          document.getElementById("lightbox-container").classList.remove("showcontainer");
        }
        else { // LIGHTBOX OFF
          var currentEventTarget = document.activeElement;
          if(currentEventTarget.tagName=='A'){
            var entertargetchild = currentEventTarget.childNodes;
            if(entertargetchild[0].tagName=='IMG'){
              var hrefofparent = currentEventTarget.getAttribute("href");
              document.getElementById("lightbox-cont-img").setAttribute("src", hrefofparent);
    
              document.getElementById("lightbox-container").classList.add("showcontainer");
              document.getElementById("lightbox-cont-img").focus();
            }
          }
    
        }
      }
      else if(event.keyCode==9) { // TAB key pressed
        if(document.getElementById("lightbox-container").classList.contains("showcontainer")){ // LIGHTBOX ON
          document.getElementById("lightbox-container").classList.remove("showcontainer");
        }
      }
      else if(event.keyCode==37) { // Left arrow key
        if(document.getElementById("lightbox-container").classList.contains("showcontainer")){ // LIGHTBOX ON
          // first get the URL of image displayed in the LIGHT BOX
          var currimgsrc = document.getElementById("lightbox-cont-img").getAttribute("src");
    
          // now match the sequence number in the array 
          var serialofarray = 0;
          for(k=0;k<allimgurlarray.length;k++){
            if(currimgsrc == allimgurlarray[k][2]){
              serialofarray = allimgurlarray[k][0];
            }
          }
    
          // with LEFT arrow, we are supposed to reduce the sequence and then use its ATTR SRC to LIGHT BOX
          if(serialofarray<=0){
            serialofarray = allimgurlarray.length - 1;
          }
          else {
            serialofarray = serialofarray - 1;
          }
          console.log("Left Arrow : "+serialofarray);
          document.getElementById("lightbox-cont-img").setAttribute("src", allimgurlarray[serialofarray][2]);
    
        }
      }
      else if(event.keyCode==39) { // RIGHT Arrow
        if(document.getElementById("lightbox-container").classList.contains("showcontainer")){
          // first get the URL of image displayed in the LIGHT BOX
          var currimgsrc = document.getElementById("lightbox-cont-img").getAttribute("src");
    
          // now match the sequence number in the array 
          var serialofarray = 0;
          for(l=0;l<allimgurlarray.length;l++){
            if(currimgsrc == allimgurlarray[l][2]){
              serialofarray = allimgurlarray[l][0];
            }
          }
    
          // with RIGHT arrow, we are supposed to increase the sequence and then use its ATTR SRC to LIGHT BOX
          if(serialofarray>=allimgurlarray.length-1){
            serialofarray = 0;
          }
          else {
            serialofarray = serialofarray + 1;
          }
          console.log("Right Arrow : "+serialofarray);
          document.getElementById("lightbox-cont-img").setAttribute("src", allimgurlarray[serialofarray][2]);
        }
      }
      else { // If any key other than ESC is pressed
    
        if(document.getElementById("lightbox-container").classList.contains("showcontainer")){
          document.getElementById("lightbox-container").classList.remove("showcontainer");
        }
      }
    }
    
    // through this we are handling the CLICK ON IMAGE events
    document.onclick= function(event) {
      overlaypop(event);
    };
    function overlaypop(event) {
      if (event===undefined) event= window.event;
      var targettag = event.target;
      var targetparent = event.target.parentNode;
      if(targettag.tagName=='IMG'){
        if(targetparent.nodeName=='A'){
          event.preventDefault();
          var hrefofparent = targetparent.getAttribute("href");
          //alert('clicked on '+ targettag.tagName + ' parent name is ' + targetparent.nodeName + ' and URL is ' + hrefofparent);
          document.getElementById("lightbox-cont-img").setAttribute("src", hrefofparent);
          document.getElementById("lightbox-container").classList.add("showcontainer");
          document.getElementById("lightbox-cont-img").focus();
        }
      }
    }
    function hideoverlay() {
      document.getElementById('lightbox-container').classList.remove('showcontainer')
    }
    

    With the Javascript above, we wish to achieve following purposes.

    1. Popup image on full screen with a translucent black background when any image is Touched, Clicked or Pressed Entered upon after navigating to the desired image using the TAB key.
    2. Hide this Lightbox when Touched, Clicked anywhere on the screen or any key on Keyboard, except Left and Right Arrow keys, is pressed.
    3. Navigate through all the images on a webpage available in the format of with Left and Right arrow key.

    Briefly, let us see how this script achieves our purposes by understanding various parts of this Javascript.

    1. With document.querySelectorAll("a[href]"), we wish to get all the IMG tags with Parent A tag in an array named atagswithimgtag.

      • We will use this array, first to disable the default behaviour of opening A tag in a new page by using event.preventDefault().
      • Then we will use this array to create a new 2D array with name allimgurlarray to store the A tag's HREF URLs and their Index number. This allows for a better trace when using the Left and Right keys.
    2. After this, we have to handle two types of events i.e. Key press events and Touch/Click events.

      • Key Press events are handled with document.onkeydown. Here we have to Handle Enter, Tab, Esc, Right and Left arrow keys with the help of If-Else-If conditions.
      • Touch or Click Events are handled with document.onclick.
    3. We use .classList.contains to check if Lightbox is hidden or visible. And we use .classList.add and .classList.remove to show and hide the Lightbox respectively.

    4. We use document.activeElement , .tagName and .childNodes to identify the IMG tag and its parent A tag on which Enter key is pressed after using TAB key for navigation.

    5. And We use window.event, event.target, event.target.parentNode and .nodeName to identify the IMG tag and its parent A tag when the respective image is clicked or touched.

    6. To make the Lightbox more ARIA compatible we use .focus() to bring focus on the image currently displayed in the Lightbox.


    Clicking, touching or pressing any key will hide the Lightbox when it is visible.


    Check this Answer to learn in details of how this Javascript will handle general Key Press events of keys like ESC, LEFT and RIGHT arrow.

    这篇关于Javascript/CSS灯箱仅适用于第一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆