Javascript 如何将jQuery变量用于此图像库覆盖?

Javascript 如何将jQuery变量用于此图像库覆盖?,javascript,jquery,css,image,gallery,Javascript,Jquery,Css,Image,Gallery,所以我正在制作一个公文包画廊,作为我为一个小练习而建立的网站的一部分。 在hover上,我试图获得一个覆盖,因为这在手机上不起作用,所以我认为让jquery后退是个好主意。这是我的代码: $(document).ready(function(){ $('.overlay-1').mouseenter(function() { $(this).css('opacity', '1') $(this).mouseleave(function() { $(thi

所以我正在制作一个公文包画廊,作为我为一个小练习而建立的网站的一部分。 在hover上,我试图获得一个覆盖,因为这在手机上不起作用,所以我认为让jquery后退是个好主意。这是我的代码:

    $(document).ready(function(){ 
  $('.overlay-1').mouseenter(function() {
    $(this).css('opacity', '1')
    $(this).mouseleave(function() {
      $(this).css('opacity', '0')
    });
  });
  $('.overlay-2').mouseenter(function() {
    $(this).css('opacity', '1')
    $(this).mouseleave(function() {
      $(this).css('opacity', '0')
    });
  });
  $('.overlay-3').mouseenter(function() {
    $(this).css('opacity', '1')
    $(this).mouseleave(function() {
      $(this).css('opacity', '0')
    });
  });
  });
它以这种方式继续进行,以便用户在单击某个图像时可以看到覆盖图。肯定有更好的方式来写这一切吗?也许使用变量,我不确定


谢谢大家

我会给每个覆盖层提供相同的类,然后切换一个类,该类在
点击
时降低/提高
不透明度
(而不是
mouseenter
/
mouseleave
,因为它用于移动回退)。例如:

单击要添加/删除的新类:

.opacity-lower {
    opacity: 0;
}
JQuery-切换类

 $(document).ready(function () {
       $('.overlays').click(function () {
           $(this).toggleClass('opacity-lower');
       });
   });

你不确定,为什么不试试。这只是代码。把那些废话打破,让它变得更好。。更好的是,当时间流逝,你获得更多经验时,你会变得更聪明;)欢迎来到stackoverflow,happy Coding您走在正确的轨道上,很高兴您意识到可能有更好的方法。一个很好的经验法则是,当你看到重复的代码时,比如你的每个鼠标进入和离开的内部,你可以将其分解成一个函数来保持你的代码“干涸”。我会考虑使用jquery“.on”方法,您可以不太具体地使用选择器。您可以编辑您的答案来解释这是如何解决问题的吗?
function show() {$(this).css('opacity', 1);}
function hide() {$(this).css('opacity', 0);}

[1,2,3].forEach(function(num) {
    $('overlay-'+num).mouseenter(show).mouseleave(hide);
});