我正在创建一个包含多个图片的图库,您可以点击一个小缩略图,该图片的更大版本将会打开。
如果移动光标,一旦打开,图像将在y轴上跟随您。与https://www.zara.com/es/es/chaqueta-denim-combinada-pC33052724001.html?v1=5161517&v2=269184
类似我的问题: 一切都工作正常,但是当你第一次打开图像并移动光标时,我正试图纠正一个“跳跃”。 发生这种情况是因为“.image-zoom img”(新的大图像)的高度仍未定义。
https://jsfiddle.net/z1jwyjur/2/
var h = 0;
function zoomTracking(event){
h = $('.image-zoom img').height();
var vptHeight = $(window).height();
var y = -((h - vptHeight) / vptHeight) * event.clientY;
$('.image-zoom img').css('top', y + "px");
console.log(h);
}
$(function() {
$('#grid a').click(function(e) {
// Currently "image zoom img" src is empty. So we give him a value, the big version of the image we click.
var changeSrc = $(this).attr('href');
$('.image-zoom img').attr('src', changeSrc);
// We make appear "image zoom"
$('.image-zoom').fadeIn();
// Here, the point is to get the height of the new big version of the image, and declare that height as "h". Not working...
h = $('.image-zoom img').height();
zoomTracking(e);
return false;
});
$('.image-zoom').mousemove(function(e) {
zoomTracking(e);
});
$('.image-zoom').click(function() {
$('.image-zoom').fadeOut();
});
});
基本上我认为我需要的是在src改变后获得新大图像的高度。
备注:在jsfiddle上,我试图纠正的“跳转”仅在您第一次点击时发生。因为第二次已经知道了身高。 /画廊将有不同宽高比的不同图像。
知道怎么解决这个问题吗?提前谢谢。
答案 0 :(得分:1)
等待图像加载之前"打开"缩放版本。
此时高度将可用,您可以在zoomTracking
中访问它,因此您可以摆脱全局变量h
function zoomTracking(event){
var imageZoom = $('.image-zoom img');
var h = imageZoom.height();
var startPos = imageZoom.data("pointerStartPosY");
if (startPos === undefined) {
startPos = event.clientY;
imageZoom.data("pointerStartPosY", startPos);
}
var vptHeight = $(window).height();
var y = -((h - vptHeight) / vptHeight) * (startPos - event.clientY);
imageZoom.css('top', y + "px");
}
$(function() {
$('.image-zoom img').on("load", function(e) {
$('.image-zoom').fadeIn();
});
$('#grid a').click(function(e) {
$('.image-zoom img').attr('src', this.href)
.data("pointerStartPosY", undefined);
return false;
});
$('.image-zoom').mousemove(function(e) {
zoomTracking(e);
});
$('.image-zoom').click(function() {
$('.image-zoom').fadeOut();
});
});
答案 1 :(得分:0)
我建议您直接引用该元素:
$("#my_img").height();
其中,
<img src="https://cdn.dribbble.com/users/226242/screenshots/3871814/attachments/878728/thumbnail/1976_chevrolet_blazer_fullview.jpg" id="my_img"></a>