Как мне применить лупу к нескольким изображениям на одной странице? - PullRequest
0 голосов
/ 27 февраля 2020

// magnify hover
function magnify(imgID, zoom) {
  var img, glass, w, h, bw;
  img = document.getElementById(imgID);
  /*create magnifier glass:*/
  glass = document.createElement("DIV");
  glass.setAttribute("class", "img-magnifier-glass");
  /*insert magnifier glass:*/
  img.parentElement.insertBefore(glass, img);
  /*set background properties for the magnifier glass:*/
  glass.style.backgroundImage = "url('" + img.src + "')";
  glass.style.backgroundRepeat = "no-repeat";
  glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px";
  bw = 3;
  w = glass.offsetWidth / 2;
  h = glass.offsetHeight / 2;
  /*execute a function when someone moves the magnifier glass over the image:*/
  glass.addEventListener("mousemove", moveMagnifier);
  img.addEventListener("mousemove", moveMagnifier);
  /*and also for touch screens:*/
  glass.addEventListener("touchmove", moveMagnifier);
  img.addEventListener("touchmove", moveMagnifier);
  function moveMagnifier(e) {
    var pos, x, y;
    /*prevent any other actions that may occur when moving over the image*/
    e.preventDefault();
    /*get the cursor's x and y positions:*/
    pos = getCursorPos(e);
    x = pos.x;
    y = pos.y;
    /*prevent the magnifier glass from being positioned outside the image:*/
    if (x > img.width - (w / zoom)) {x = img.width - (w / zoom);}
    if (x < w / zoom) {x = w / zoom;}
    if (y > img.height - (h / zoom)) {y = img.height - (h / zoom);}
    if (y < h / zoom) {y = h / zoom;}
    /*set the position of the magnifier glass:*/
    glass.style.left = (x - w) + "px";
    glass.style.top = (y - h) + "px";
    /*display what the magnifier glass "sees":*/
    glass.style.backgroundPosition = "-" + ((x * zoom) - w + bw) + "px -" + ((y * zoom) - h + bw) + "px";
  }
  function getCursorPos(e) {
    var a, x = 0, y = 0;
    e = e || window.event;
    /*get the x and y positions of the image:*/
    a = img.getBoundingClientRect();
    /*calculate the cursor's x and y coordinates, relative to the image:*/
    x = e.pageX - a.left;
    y = e.pageY - a.top;
    /*consider any page scrolling:*/
    x = x - window.pageXOffset;
    y = y - window.pageYOffset;
    return {x : x, y : y};
  }
}
/* Initiate Magnify Function
with the id of the image, and the strength of the magnifier glass:*/
magnify("mag", 5);
* {box-sizing: border-box;}

.img-magnifier-container {
  position:relative;
}

.img-magnifier-glass {
  position: absolute;
  z-index: 3;
  border: 1px solid #000;
  border-radius: 20%;
  cursor: none;
  /*Set the size of the magnifier glass:*/
  width: 120px;
  height: 130px;
  opacity:0;
  pointer-events:none;
}
a:hover .img-magnifier-glass{
  opacity:1;
  pointer-events:initial;
}
<table class="img-magnifier-container" width="115" border="0" cellpadding="0" cellspacing="0" style="display: inline-block"><tr><td width="115" style="text-align: center"><center><a href="https://www.imdb.com/title/tt0478970/" title="Ant-Man (2015)" target="_blank"><img class="cover" width="115" height="133" border="0" id="mag" class="pstrart" id="pstr" src="https://images2.static-bluray.com/movies/covers/238380_front.jpg" style=""></a></center><center><input type="checkbox" name="movieboxes" value="Ant-Man" style="width: 15px; height: 15px; margin: 0px;">
<img title="United Kingdom" border="2" class="flag" id="flgborder" src="https://cdn.discordapp.com/attachments/530906893443399683/665554365897244693/union-jack-26119_960_720.png" style="width: 25px; height: 17px;">
</center></td></tr></table>&nbsp;
&nbsp;
<table class="img-magnifier-container" width="115" border="0" cellpadding="0" cellspacing="0" style="display: inline-block"><tr><td width="115" style="text-align: center"><center><a href="https://www.imdb.com/title/tt6644200/" title="A Quiet Place (2018)" target="_blank"><img class="cover" width="115" height="133" border="0" id="mag" class="pstrart" id="pstr" src="https://images2.static-bluray.com/movies/covers/202637_front.jpg" style=""></a></center><center><input type="checkbox" name="movieboxes" value="A Quiet Place" style="width: 15px; height: 15px; margin: 0px;">
<img title="United Kingdom" border="2" class="flag" id="flgborder" src="https://cdn.discordapp.com/attachments/530906893443399683/665554365897244693/union-jack-26119_960_720.png" style="width: 25px; height: 17px;">
</center></td></tr></table>&nbsp;
&nbsp;

Здравствуйте,

Я недавно сделал лупу при наведении курсора, используя помощь людей на этом сайте. Тем не менее, я не знаю, как сделать так, чтобы я мог иметь увеличитель на всех изображениях, а не только на первом. Я добавил в этот пост два изображения, чтобы вы могли понять, что я имею в виду.

Спасибо за любую информацию!

1 Ответ

0 голосов
/ 27 февраля 2020

Для дальнейшего уточнения моего комментария: основная проблема заключается в том, что:

  1. У вас есть дубликаты идентификаторов и дубликаты атрибутов в нескольких элементах на вашей странице. Вы всегда должны использовать уникальные идентификаторы в документе, и вместо нескольких class атрибутов на элемент вы должны объединить их в один.
  2. Вы инициализируете логи увеличения c для одного элемента. Вам не хватает итеративной логики c для просмотра всех изображений, которые вы хотите увеличить.

Я предлагаю следующее:

  1. Исправьте ошибки DOM как указано выше. Также дайте элементам изображения, которые вы хотите увеличить, общий класс, чтобы мы могли выбрать все из них. Например, class="magnify-image", но вы можете использовать любые произвольные имена классов.
  2. Вы обновляете метод magnify(), чтобы принимать элемент изображения вместо идентификатора: это будет означать, что наш итеративный logi c может передать элемент изображения, который вы хотите увеличить напрямую. Переписав его на function magnify(img, zoom) { ... }, а затем удалите присвоение var img = ....

  3. Вы даете каждому изображению, которое хотите увеличить класс, а затем выбираете для всех этих изображений создание HTMLCollection. Выполните итерацию по этой коллекции и просто передайте элемент изображения в каждой итерации в качестве первого аргумента.

Пример итеративной логики c:

// Iterate through all images you want to magnify
const images = document.querySelectorAll('.magnify-image');
Array.from(images).forEach((image) => {
    // We pass the actual image element into the function
    magnify(image, 5);
});

Если вы абсолютно должны поддерживать ES5, тогда мы можем сделать это:

var images = document.getElementsByClassName('magnify-image');
Array.prototype.forEach.call(images, function(image) {
    // We pass the actual image element into the function
    magnify(image, 5);
});

См. подтверждение концепции:

// magnify hover
function magnify(img, zoom) {
  var glass, w, h, bw;
  /*create magnifier glass:*/
  glass = document.createElement("DIV");
  glass.setAttribute("class", "img-magnifier-glass");
  /*insert magnifier glass:*/
  img.parentElement.insertBefore(glass, img);
  /*set background properties for the magnifier glass:*/
  glass.style.backgroundImage = "url('" + img.src + "')";
  glass.style.backgroundRepeat = "no-repeat";
  glass.style.backgroundSize = (img.width * zoom) + "px " + (img.height * zoom) + "px";
  bw = 3;
  w = glass.offsetWidth / 2;
  h = glass.offsetHeight / 2;
  /*execute a function when someone moves the magnifier glass over the image:*/
  glass.addEventListener("mousemove", moveMagnifier);
  img.addEventListener("mousemove", moveMagnifier);
  /*and also for touch screens:*/
  glass.addEventListener("touchmove", moveMagnifier);
  img.addEventListener("touchmove", moveMagnifier);

  function moveMagnifier(e) {
    var pos, x, y;
    /*prevent any other actions that may occur when moving over the image*/
    e.preventDefault();
    /*get the cursor's x and y positions:*/
    pos = getCursorPos(e);
    x = pos.x;
    y = pos.y;
    /*prevent the magnifier glass from being positioned outside the image:*/
    if (x > img.width - (w / zoom)) {
      x = img.width - (w / zoom);
    }
    if (x < w / zoom) {
      x = w / zoom;
    }
    if (y > img.height - (h / zoom)) {
      y = img.height - (h / zoom);
    }
    if (y < h / zoom) {
      y = h / zoom;
    }
    /*set the position of the magnifier glass:*/
    glass.style.left = (x - w) + "px";
    glass.style.top = (y - h) + "px";
    /*display what the magnifier glass "sees":*/
    glass.style.backgroundPosition = "-" + ((x * zoom) - w + bw) + "px -" + ((y * zoom) - h + bw) + "px";
  }

  function getCursorPos(e) {
    var a, x = 0,
      y = 0;
    e = e || window.event;
    /*get the x and y positions of the image:*/
    a = img.getBoundingClientRect();
    /*calculate the cursor's x and y coordinates, relative to the image:*/
    x = e.pageX - a.left;
    y = e.pageY - a.top;
    /*consider any page scrolling:*/
    x = x - window.pageXOffset;
    y = y - window.pageYOffset;
    return {
      x: x,
      y: y
    };
  }
}

// Iterate through all images you want to magnify
const images = document.querySelectorAll('.magnify-image');
Array.from(images).forEach((image) => {
  
  magnify(image, 5);
});
* {
  box-sizing: border-box;
}

.img-magnifier-container {
  position: relative;
}

.img-magnifier-glass {
  position: absolute;
  z-index: 3;
  border: 1px solid #000;
  border-radius: 20%;
  cursor: none;
  /*Set the size of the magnifier glass:*/
  width: 120px;
  height: 130px;
  opacity: 0;
  pointer-events: none;
}

a:hover .img-magnifier-glass {
  opacity: 1;
  pointer-events: initial;
}
<table class="img-magnifier-container" width="115" border="0" cellpadding="0" cellspacing="0" style="display: inline-block">
  <tr>
    <td width="115" style="text-align: center">
      <center>
        <a href="https://www.imdb.com/title/tt0478970/" title="Ant-Man (2015)" target="_blank"><img width="115" height="133" border="0" class="cover pstrart magnify-image" src="https://images2.static-bluray.com/movies/covers/238380_front.jpg" style=""></a>
      </center>
      <center><input type="checkbox" name="movieboxes" value="Ant-Man" style="width: 15px; height: 15px; margin: 0px;">
        <img title="United Kingdom" border="2" class="flag" src="https://cdn.discordapp.com/attachments/530906893443399683/665554365897244693/union-jack-26119_960_720.png" style="width: 25px; height: 17px;">
      </center>
    </td>
  </tr>
</table>&nbsp; &nbsp;
<table class="img-magnifier-container" width="115" border="0" cellpadding="0" cellspacing="0" style="display: inline-block">
  <tr>
    <td width="115" style="text-align: center">
      <center>
        <a href="https://www.imdb.com/title/tt6644200/" title="A Quiet Place (2018)" target="_blank"><img width="115" height="133" border="0" class="cover pstrart magnify-image" src="https://images2.static-bluray.com/movies/covers/202637_front.jpg" style=""></a>
      </center>
      <center><input type="checkbox" name="movieboxes" value="A Quiet Place" style="width: 15px; height: 15px; margin: 0px;">
        <img title="United Kingdom" border="2" class="flag" src="https://cdn.discordapp.com/attachments/530906893443399683/665554365897244693/union-jack-26119_960_720.png" style="width: 25px; height: 17px;">
      </center>
    </td>
  </tr>
</table>&nbsp; &nbsp;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...