Javascript/CSS 灯箱仅对第一个元素起作用?

8

我希望在每个照片被单击时,在Javascript/CSS灯箱中打开它们。目前,只有照片列表中的第一张照片会在灯箱中打开。其他照片不会在灯箱中打开。

请问有谁可以解释/展示为什么会这样,并向我说明/展示正确的做法?

以下是我的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>

提前感谢。


3
你有重复的id(id="myImg")。页面上所有的id都必须是唯一的,这是一个严格的规则。 - Kalnode
我没有看到任何 jQuery,只有 JS。为什么要标记 jQuery? - Louys Patrice Bessette
@LouysPatriceBessette 对不起,是我的错误,我还在学习阶段,对于Jquery/Javascript的区别还有点不确定。问题已经修改过了。谢谢。 - Mike Dawson
@MikeDawson,用于类的 getElementById 的等效方法是 getElementsByClassName,请记住它返回一个项目数组,这里有更多的文档。 https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName - Philippe
@MikeDawson 如果您在帖子中提供可运行的代码示例,我们中的一些人可以更好地帮助您。请尝试将您的HTML / JS / CSS提取并粘贴到帖子中作为代码片段。 - Kalnode
显示剩余2条评论
3个回答

0

好消息是,您的图像既不需要id也不需要class

  • 监听图像周围容器的单击事件,而不是图像本身。这种技术称为事件委托,对性能更好。我们不是为每个图像绑定n个事件侦听器,而是在图像的容器上添加一个侦听器
  • 单击时,获取target元素的srcalt,并将其传递给showModal函数。用传递的值填充模态图像的srcalt

以后的建议

看起来您计划在模态框中显示基于传入的alt值的标题。考虑在模态框中使用figcaption

HTML或图例说明元素表示其父元素其余内容的标题或图例说明。

这里有一个示例供您开始。我将把模态/模态内容的样式留给您。我在模态中使用了一个figure元素来提高语义价值。

演示

var modal = document.getElementById('myModal');

var imgContainer = document.querySelector('.imageContainer');
var modalContentImage = modal.querySelector('.modal-content-image');

imgContainer.addEventListener('click', function(e) {
  if (e.target.nodeName === "IMG") {
    showModal({src: e.target.src, alt: e.target.alt})
  }
});

function showModal(opts) {
  modal.style.display = "block";
  modalContentImage.setAttribute('src', opts.src);
  modalContentImage.setAttribute('alt', opts.alt);
}

// 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";
}
#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-image {
  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%;
  }
}

/* Presentation only */

.imageContainer {
  min-height: 100vh;
  display: flex;
  align-items: flex-end;
  overflow-x: auto;
}

.imageContainer img {
  width: 100px;
  flex-shrink: 0;
}

html,
body {
  margin: 0;
  padding: 0;
}
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <figure class="modal-content">
    <img class="modal-content-image" alt>
  </figure>
</div>

<div class="imageContainer">
  <img src="https://picsum.photos/300/300/?image=0" alt="CPU 1">
  <img src="https://picsum.photos/300/300/?image=1" alt="CPU 2">
  <img src="https://picsum.photos/300/300/?image=2" alt="CPU 3">
  <img src="https://picsum.photos/300/300/?image=3" alt="CPU 4">
  <img src="https://picsum.photos/300/300/?image=4" alt="CPU 5">
  <img src="https://picsum.photos/300/300/?image=5" alt="CPU 6">
  <img src="https://picsum.photos/300/300/?image=6" alt="CPU 7">
  <img src="https://picsum.photos/300/300/?image=7" alt="CPU 8">
  <img src="https://picsum.photos/300/300/?image=8" alt="CPU 9">
  <img src="https://picsum.photos/300/300/?image=9" alt="CPU 10">
  <img src="https://picsum.photos/300/300/?image=10" alt="CPU 11">
  <img src="https://picsum.photos/300/300/?image=11" alt="CPU 12">  
</div>

jsFiddle


0

你的代码包含多个id,请尝试使用class,并通过document.getElementsByClassName获取图像类,然后在循环内绑定每个图像的点击事件,尝试将你的php代码添加到下面修订后的代码中。

// 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 imgs = document.getElementsByClassName("myImg");
var modalImg = document.getElementById("img01");

for(var i = 0; i < imgs.length; i++)
{
  imgs[i].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";
}
#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%;
  }
}
    <div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
    <div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
    <div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
    <div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
    <div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>
    <div class="profile_gallery_image"><img class="myImg" src='https://via.placeholder.com/150' height="100%" width="100%" /></div>



<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="img01">
</div>


0

纯Javascript Lightbox / 图片弹出框

我想分享一个完全符合ARIA导航指南的纯Javascript Lightbox或图片弹出框,它非常轻量级且易于实现,因为:

  1. 它不需要任何JQUERY,因此可以避免额外的CDN导入请求和整个JQUERY库的缓冲。
  2. 这是一种部署并忘记的设计,我们只需要添加与LIGHTBOX相关的HTML、CSS和JAVASCRIPT,而无需将唯一的ID或CLASS添加到图像或其父A标签的HTML标记中。因此,稍后从您现有的网页中添加或删除图像将不需要更改Javascript或IMG/A标记的ID/CLASS属性。

  1. 为了实现这一点,先决条件是IMG标记中的所有图像都应该是父级A标记的唯一子节点,如<a title="" href=""><img alt="" src=""/></a>

    • 此外,需要注意的一点是,在A标记和IMG标记的开放和关闭之间不应该有空格,并且它应该显示为<a><img/></a>

    • 由于页面下载时只加载IMG标记图像而不加载A标记,因此为所有IMG标记创建父级A标记允许在IMG标记中存储较小尺寸的图像和在父级A标记中存储相同图像的较大尺寸。

    • 将IMG标记与Loading="lazy"结合使用可以进一步加快页面加载速度。

  2. 当在网页上实现时,这个Lightbox的工作非常简单,即您可以点击、触摸或按下IMG标记上的任何图像,然后弹出一个模态框或Lightbox来显示相同URL图像或存储在IMG标记的父级A标记中的不同图像。

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

现在让我们看一些代码:


这是一个包含图像和指向其他页面的URL的A标签的示例HTML

<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>

假设我们的网页上有五张图片,它们都是以上面定义的格式<a title="" href=""><img alt="" src=""/></a>显示的。

为了展示这个Lightbox是动态的,我们还包括了一个额外的<a href="https://anubhavyadavjovian.blogspot.com/">Anubhav yadav</a>,当单击、触摸或按Enter键时,它将像一个普通的A Href标签一样运行,而只有IMG标签作为子元素的A标签将弹出Lightbox。


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

上面的真实HTML代码是为我们的灯箱设计的,其中一个ID为"lightbox-container"的元素作为半透明黑色背景,另一个ID为"lightbox-cont-img"的元素则用于显示图片。


#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;
}

以上是用于 Lightbox 装饰以及出现和消失时创建过渡效果的真实 CSS
// 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')
}

通过上述Javascript,我们希望实现以下目的。

  1. 当触摸、点击或按下键盘上的Enter键后进入所需图像时,弹出全屏幕带半透明黑色背景的图像。
  2. 除了左右箭头键外,在屏幕上任何位置触摸、点击或按下键盘上的任意键都会隐藏此灯箱。
  3. 使用左右箭头键浏览网页上所有以 格式提供的图像。

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

使用document.querySelectorAll("a[href]"),我们希望获取所有包含IMG标签的父级A标签的数组,并将其命名为atagswithimgtag
我们将使用此数组,首先通过使用event.preventDefault()来禁用打开新页面的默认行为。
然后,我们将使用此数组创建一个名为allimgurlarray的新二维数组,以存储A标签的HREF URL和它们的索引号。这样可以更好地跟踪使用左右键时的情况。
之后,我们必须处理两种类型的事件,即按键事件和触摸/点击事件。
按键事件使用document.onkeydown进行处理。在这里,我们必须使用If-Else-If条件来处理Enter、Tab、Esc、Right和Left箭头键。
触摸或点击事件使用document.onclick进行处理。
我们使用.classList.contains来检查Lightbox是否隐藏或可见。我们使用.classList.add.classList.remove来分别显示和隐藏Lightbox。
我们使用document.activeElement.tagName.childNodes来识别在使用TAB键进行导航后按下Enter键的IMG标签及其父级A标签。
当单击或触摸相应图像时,我们使用window.eventevent.targetevent.target.parentNode.nodeName来识别IMG标签及其父级A标签。
为使Lightbox更符合ARIA,我们使用.focus()将焦点放在当前显示在Lightbox中的图像上。

当 Lightbox 可见时,单击、触摸或按下任意键都将隐藏它。


查看本答案以详细了解此JavaScript将如何处理诸如 ESC LEFT RIGHT 箭头等键的一般按键事件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接