Я хочу установить линзу на панели предварительного просмотра и показать идеальное изображение в zoomer div, но не могу это исправить. Я просто конвертировал свой код из какого-то примера javascript, и я плохо разбираюсь в javascript, поэтому мне нужна помощь некоторых экспертов!
мои ожидания, как на изображении ниже:
мои текущие разработки, такие как:
$(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">
У меня это работает. Вы уверены, что добавили CSS? Пример CodePen
вы можете использовать этот компонент. elevateweb.co.uk/image-zoom/examples его мощный и лучший. надеюсь, что это помогло
вы хотите добиться изменения изображения или предварительного просмотра при наведении на то же изображение, например (w3schools.com/howto/howto_js_image_zoom.asp) w3schools, о котором вы упомянули?
Я хочу установить 5 изображений для отображения большого размера с эффектом масштабирования, но здесь есть только одно изображение, как я могу установить еще 4 небольших изображения, и когда я нажимаю на предварительный просмотр небольшого изображения, div меняет фон с этим изображением, например эффект масштабирования продукта www.aliexpress.com



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Вы пропустили 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.info(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>я не скучаю по css! я просто сокращаю код. Попытайтесь понять, что я хочу показать 5 изображений продукта, а затем каждое изображение onclick должно отображаться в предварительном просмотре div, а затем onmousemove будет отображаться эффект масштабирования. но здесь я не могу добавить триггер клика набора изображений
разве это невозможно сделать только в одном div предварительного просмотра? я думаю, теперь ты понимаешь
Рохан Кумар! ты разбудил gr8 и чувствуешь себя счастливым, что пытаешься мне помочь! Я обновляю детали своего вопроса, пожалуйста, посмотрите его, и я уверен, что теперь вы можете отправить меня к успеху! Спасибо
Извините, но не совсем понятно, что вы ищете. Не могли бы вы дать дополнительные объяснения?