首页 > 代码库 > 模仿Bootstrap插件的放大镜插件

模仿Bootstrap插件的放大镜插件

/**该插件的使用基于jQuery**/

var mymagnifier=function(opts){
opts = mymagnifier.prototype.extendObj(mymagnifier.prototype.defaults,opts);
mymagnifier.prototype.magnifier(opts);
}
/**默认参数块**/ 
mymagnifier.prototype.defaults = {
img:"img", 
bigimg:"bigs",
mark:"mark"
};

mymagnifier.prototype.magnifier=function(opts){
var img = document.getElementById(opts.img);
var bigimg = document.getElementById(opts.bigimg);
var mark = document.getElementById(opts.mark);
var magnifier=img.parentNode;
console.log(magnifier.className+"+"+magnifier.getBoundingClientRect().left+"+"+magnifier.getBoundingClientRect().top);
var x,y,l,t,L,T,mL,mT;
img.onmouseover=function(){
mark.style.display="block";
bigimg.style.display="block";
}
img.onmouseout=function(){
mark.style.display="none";
bigimg.style.display="none";
}
img.onmousemove=function(e){
//获取鼠标相对浏览器的坐标
x=e.clientX;
y=e.clientY;
//console.log("x"+x,"y"+y)
l=img.offsetLeft;
t=img.offsetTop;
mark.style.left=(x-l-mark.offsetWidth/2-magnifier.getBoundingClientRect().left)+‘px‘;
mark.style.top=(y-t-mark.offsetHeight/2-magnifier.getBoundingClientRect().top)+‘px‘;
// 移动区边界距离边界的距离
mL=mark.offsetLeft;
mT=mark.offsetTop;
//最小范围
/*console.log("mL"+mL,"mT"+mT)*/
if(mL<=0){
mark.style.left="0";
}
if(mT<=0){
mark.style.top="0"
}
// 最大范围
if(mL>=img.offsetWidth-mark.offsetWidth){
mark.style.left=img.offsetWidth-mark.offsetWidth+"px";
}
if(mT>=img.offsetHeight-mark.offsetHeight){
mark.style.top=img.offsetHeight-mark.offsetHeight+"px";
}
//显示区的宽高
L=bigimg.offsetWidth;
T=bigimg.offsetHeight;
// console.log(L,T);
//获取放大的倍数
bigimg.style.left="-"+(mL/(img.offsetWidth/L))+"px";
bigimg.style.top="-"+(mT/(img.offsetHeight/T))+"px";
// console.log(bigimg.style.left,bigimg.style.top)
}
}


//js继承
mymagnifier.prototype.cloneObj=function(oldObj) { //复制对象方法
if (typeof(oldObj) != ‘object‘) return oldObj;
if (oldObj == null) return oldObj;
var newObj = new Object();
for (var i in oldObj)
newObj[i] = mymagnifier.prototype.cloneObj(oldObj[i]);
return newObj;
};
mymagnifier.prototype.extendObj=function() { //扩展对象
var args = arguments;
if (args.length < 2) return;
var temp = mymagnifier.prototype.cloneObj(args[0]); //调用复制对象方法
for (var n = 1; n < args.length; n++) {
for (var i in args[n]) {
temp[i] = args[n][i];
}
}
return temp;
}
HTMLElement.prototype.MYmagnifier = mymagnifier;
var magnifier_box=document.getElementsByClassName("magnifier");
for(var i=0;i<magnifier_box.length;i++){
magnifier_box[i].MYmagnifier();
}

 

模仿Bootstrap插件的放大镜插件