Исправление логики увеличения изображения - PullRequest
0 голосов
/ 29 августа 2018

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

мои ожидания, как на картинке ниже:

enter image description here

моя текущая разработка вроде:

$(function(){
$('.previewPane, #zoomer').css('background-image','url('+$('.imgkey').first().attr('src')+')');
$('.imgkey').click(function(){
$('.previewPane').css('background-image','url('+$(this).attr('src')+')');
			});
$('.previewPane').mousemove(function(ev){
$('#zoomer').css('display','inline-block');
var img = $(this).css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1');
var posX = ev.offsetX ? (ev.offsetX) : ev.pageX - $(this).offset().left;
var posY = ev.offsetY ? (ev.offsetY) : ev.pageY - $(this).offset().top;
$('#zoomer').css('background-position',((-posX * 3) + "px " + (-posY * 3) + "px"));
$('#zoomer').css('background-image','url('+img+')');
			});
$('.previewPane').mouseleave(function(){$('#zoomer').css('display','none');});
		});
.imgkey{width:50px;height:50px;border:1px solid #ddd;}
.previewPane{display:inline-block;border:1px solid #ddd;width:250px;height:250px;cursor:crosshair;background-repeat:no-repeat;background-position:center;background-size:100% 100%}
#zoomer{display:none;background-repeat:no-repeat;border:1px solid #ddd;width:250px;height:250px;z-index:1000;}
<!DOCTYPE html>
	<html>
	<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>
  <body>
	<main>
		<div class="previewPane"></div><div id="zoomer"></div>
		<div class="imgline">
			<img class="imgkey" src="https://cdn.shopify.com/s/files/1/0622/2101/products/product-image-496137782_800x.jpg?v=1519622126">
			<img class="imgkey" src="https://images-na.ssl-images-amazon.com/images/I/61IPCXn13AL._SX385_.jpg">
			<img class="imgkey" src="https://http2.mlstatic.com/celular-smartphone-caterpillar-s60-negro-32-gb-D_NQ_NP_940281-MCO26572973595_122017-F.jpg">
		</div>
	</main>

Я также пробую ваш код с простым изменением, например: просто добавьте эти две строки перед "$ ('. Preview'). Each (function () {", но не повезло.

$('.img-zoom-container').html('<div class="preview"><img class="image" src="'+$('.Key').first().attr('src')+'"></div>');


$('.Key').click(function(){
    $('.img-zoom-container').html('<div class="preview"><img class="image" src="'+$(this).attr('src')+'"></div>');
});

и изображения вне 'img-zoom-container', такие как:

<img class="Key" src="https://www.w3schools.com/howto/img_girl.jpg" width="200" height="200">
<img class="Key" src="https://placeimg.com/640/480/animals" width="200" height="200">
<img class="Key" src="https://placeimg.com/640/480/arch" width="200" height="200">

1 Ответ

0 голосов
/ 29 августа 2018

Вы пропустили CSS из W3Schools и ваш образ src не работает,

См. Рабочий фрагмент с несколькими изображениями.

$('.preview').each(function() {
  var lens, cx, cy, img, result;
  img = $(this).find('img.image')[0];
  result = document.getElementById('result');
  /*create lens:*/
  lens = document.createElement("div");
  lens.setAttribute("class", "img-zoom-lens");
  /*insert lens:*/
  img.parentElement.insertBefore(lens, img);
  /*calculate the ratio between result DIV and lens:*/
  cx = result.offsetWidth / lens.offsetWidth;
  cy = result.offsetHeight / lens.offsetHeight;
  /*set background properties for the result DIV:*/
  
  /*execute a function when someone moves the cursor over the image, or the lens:*/
  $(lens).on('mousemove touchmove', moveLens);
  $(img).on('mousemove touchmove', moveLens);

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

  function moveLens(e) {
    var pos, x, y;
    result.style.backgroundImage = "url('" + img.src + "')";
      result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px";

    /*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);
    /*calculate the position of the lens:*/
    x = pos.x - (lens.offsetWidth / 2);
    y = pos.y - (lens.offsetHeight / 2);
    /*prevent the lens from being positioned outside the image:*/
    if (x > img.width - lens.offsetWidth) {
      x = img.width - lens.offsetWidth;
    }
    if (x < 0) {
      x = 0;
    }
    if (y > img.height - lens.offsetHeight) {
      y = img.height - lens.offsetHeight;
    }
    if (y < 0) {
      y = 0;
    }
    /*set the position of the lens:*/
    lens.style.left = x + "px";
    lens.style.top = y + "px";
    /*display what the lens "sees":*/
    result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px";
    console.log(result);
  }

})
* {
  box-sizing: border-box;
}

.img-zoom-container {
  
  width: 100%
}

.preview {
  display: inline-block;
  margin: 0 10px;
  position: relative;
}

.img-zoom-lens {
  position: absolute;
  border: 1px solid #d4d4d4;
  /*set the size of the lens:*/
  width: 40px;
  height: 40px;
}

.img-zoom-result {
  border: 1px solid #d4d4d4;
  /*set the size of the result div:*/
  width: 300px;
  height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
</script>

<h1>Image Zoom</h1>
<p>Mouse over the image:</p>
<div class="img-zoom-container">
  <div class="preview"><img class="image" src="https://www.w3schools.com/howto/img_girl.jpg" width="200" height="200"></div>
  <div class="preview"><img class="image" src="https://placeimg.com/640/480/animals" width="200" height="200"></div>
  <div class="preview"><img class="image" src="https://placeimg.com/640/480/arch" width="200" height="200"></div>

</div>

<div class="img-zoom-result" id="result"></div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...