首先通过绑定点击事件来打开图片预览。当点击事件触发时,获取被点击图片的链接和标题。然后使用layer.photos()
方法来打开图片预览。在layer.photos()
方法中,通过传入一个包含图片信息的对象来配置预览的图片,其中包括图片标题和链接。anim
参数用于指定图片预览的动画效果。
在success
回调函数中,实现了以鼠标位置为中心的滚动放大缩小功能。通过监听mousewheel
事件,根据鼠标滚动的方向来计算图片的缩放比例,进而调整图片的宽度、高度和位置。通过$(".layui-layer-photos")
、$("#layui-layer-photos")
和$("#layui-layer-photos>img")
来获取相应的元素并进行样式调整。
<div>
<img class="preview-img" src="{$v.image}" style="width: 278px;" />
</div>
// 绑定点击事件,打开图片预览
$('.preview-img').on('click', function() {
var imgSrc = $(this).attr('src'); // 获取图片链接
var title = $(this).attr('alt'); // 获取图片标题
// 调用layer.photos()方法,打开图片预览
layer.photos({
photos: {
title: title, // 图片标题
data: [{
src: imgSrc // 图片链接
}]
},
anim: 5, // 图片预览的动画效果
//添加旋转按钮
tab: function() {
num = 0;
// $("#layui-layer-photos").append(
// //'/Content/images/TowardsLeftRotate.png'(逆时针)
// //'/Content/images/TowardsRightRotate.png'(顺时针)
// //'/Content/images/rotate.png'(双向旋转)
// `<div class="pootosIcon" style="position:absolute;width:100%;text-align:center;bottom:0px;cursor:pointer;">
// <img src="/Content/images/rotate.png" style="width:32px;height:32px;">
// </div>`);
},
success: function() {
//以鼠标位置为中心的图片滚动放大缩小
$(document).on("mousewheel", ".layui-layer-photos", function (ev) {
var oImg = this;
var ev = event || window.event;//返回WheelEvent
//ev.preventDefault();
var delta = ev.detail ? ev.detail > 0 : ev.wheelDelta < 0;
var ratioL = (ev.clientX - oImg.offsetLeft) / oImg.offsetWidth,
ratioT = (ev.clientY - oImg.offsetTop) / oImg.offsetHeight,
ratioDelta = !delta ? 1 + 0.1 : 1 - 0.1,
w = parseInt(oImg.offsetWidth * ratioDelta),
h = parseInt(oImg.offsetHeight * ratioDelta),
l = Math.round(ev.clientX - (w * ratioL)),
t = Math.round(ev.clientY - (h * ratioT));
//设置相册层宽高
$(".layui-layer-photos").css({ width: w, height: h, left: l, top: t });
//设置图片外div宽高
$("#layui-layer-photos").css({ width: w, height: h });
//设置图片宽高
$("#layui-layer-photos>img").css({ width: w, height: h });
});
//点击旋转按钮旋转图片
$(document).on("click", ".pootosIcon img", function (e) {
//+90为向右旋(顺时针),-90为向左旋(逆时针)
num = (num + 90) % 360;
//旋转之后背景色设置为黑色,不然在旋转长方形图片时会留下白色空白
//$(".layui-layer.layui-layer-page.layui-layer-photos").css('background', 'black');
$("#layui-layer-photos").css('transform', 'rotate(' + num + 'deg)');
});
},
});
});