jquery图片预览插件实现方法详解

2020-05-23 06:20:25易采站长站整理

var LightBox = function(lightbox) {

var _this_ = this;
// 保存单个lightbox组件
this.lightbox = lightbox;
// 默认配置参数
this.config = {
// 弹框的默认高度
"boxHeight" : 600,
// 弹框的默认宽度
"boxWidth" : 800,
// 页面显示的缩略图默认高度
"thumbnailWidth" : 80,
// 页面显示的缩略图默认宽度
"thumbnailHeight" : 80
};

var userConfig = lightbox.config;
if (userConfig) { // 如果传入了用户设置,则使用用户设置;否则使用默认配置
$.extend(this.config, userConfig);
}

var imgObj = lightbox.imgObj; // 需要有图片预览功能的img对象(jquery对象)
imgObj.width(this.config.thumbnailWidth).height(this.config.thumbnailHeight); // 设置缩略图大小
// 设置图片点击后显示预览图
imgObj.click(function() {
_this_.invoke($(this), _this_.config);
});
};

LightBox.prototype = {
// 事件驱动方法
invoke : function(imgObj, config) {
var _this_ = this;
// 存放图片信息的对象
this.imgInfo = this.getImgInfo(imgObj[0].src, config);
var promptHtml = '<div><div id="light" class="white_content">'
+ '<div class="close"><a class="removePrompt" href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >关闭</a> <a class="resetPosition" href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >重置</a>'
+ ' <a class="downloadImg" href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" >下载</a></div>'
+ '<div class="con"></div></div>'
+ '<div id="fade" class="black_overlay"></div></div>';

var imgHtml = '<img id="lightImg" class="ui-content" src="' + this.imgInfo.imgPath + '"/>';
var $imgHtml = $(imgHtml).width(this.imgInfo.imgActualWidth).height(this.imgInfo.imgActualHeight);
var $promptHtml = $(promptHtml);

var $whiteContent = $promptHtml.find(".white_content");
var $con = $promptHtml.find(".con");
// 设置自定义的弹框高宽
$whiteContent.width(config.boxWidth).height(config.boxHeight);
$con.width(config.boxWidth).height(config.boxHeight);
$imgHtml.appendTo($con);

var $body = $("body");
$promptHtml.appendTo($body);

// 设置提示框的样式
var returnData = this.promptPosition($promptHtml);
this.imgInfo.imgOriginTop = returnData.imgOriginTop;
this.imgInfo.imgOriginLeft = returnData.imgOriginLeft;

// 绑定事件
$promptHtml.find(".resetPosition").off("click").on("click", function() { // 重置按钮
_this_.revertImg($promptHtml, _this_.imgInfo);
});
$promptHtml.find(".removePrompt").off("click").on("click", function() { // 关闭按钮
$promptHtml.remove();