1、公共文件
var Utils=(function () {
return {
//样式复制
ce:function(type , style){
var elem = document.createElement(type) ;
if(style) Object.assign(elem.style , style) ;
return elem ;
} ,
}
})();
2、准备工作-定义
var mask , //移动div
zoom ; //大div
const MINI_WIDTH = 450 ,
MASK_WIDTH = 303 ,
ZOOM_WIDTH = 540 ,
MINI_LEFT = 150 ,
MINI_TOP = 300 ;
3、代码实现
init() ;
function init(){
createLeftMini() ;
createRightZoom() ;
}
function createLeftMini(){
var div = Utils.ce("div" , { //创建小div
width: MINI_WIDTH + "px" ,
height: MINI_WIDTH + "px" ,
backgroundImage: "url(img/fdj/phone.jpg)" ,
backgroundRepeat: 'no-repeat',
backgroundSize: "100% 100%" ,
border: "1px solid #ccc" ,
position: "absolute" ,
top: MINI_TOP + "px" ,
left: MINI_LEFT + "px"
}) ;
mask = Utils.ce("div" , { //移动div
width: MASK_WIDTH + "px" ,
height: MASK_WIDTH + "px" ,
backgroundColor: "rgba(255,220,0,0.3)" ,
position: "absolute" ,
display: "none"
}) ;
div.appendChild(mask) ;
document.body.appendChild(div) ;
div.addEventListener("mouseenter" , mouseHandler) ;
div.addEventListener("mouseleave" , mouseHandler) ;
}
function createRightZoom(){
zoom = Utils.ce("div" , {
width: ZOOM_WIDTH + "px" ,
height: ZOOM_WIDTH + "px" ,
backgroundImage: "url(img/fdj/phone.jpg)" ,
backgroundRepeat: 'no-repeat',
backgroundSize: `${ZOOM_WIDTH * MINI_WIDTH / MASK_WIDTH}px ${ZOOM_WIDTH * MINI_WIDTH / MASK_WIDTH}px`,
backgroundPositionX: "0px" ,
backgroundPositionY: "0px" ,
position: "absolute" ,
left: MINI_LEFT + MINI_WIDTH + "px" ,
top: MINI_TOP + "px" ,
display: "none"
})
document.body.appendChild(zoom) ;
}
function mouseHandler(e){
if(e.type === "mouseenter"){
mask.style.display = "block" ;
zoom.style.display = "block" ;
this.addEventListener("mousemove" , mouseHandler) ;
}else if(e.type === "mouseleave"){
mask.style.display = "none" ;
zoom.style.display = "none" ;
this.removeEventListener("mousemove" , mouseHandler) ;
}else if(e.type === "mousemove"){
moveMask(e.clientX , e.clientY , this) ;
//传进鼠标距离可视窗口的X和Y值,和父容器
zoomBackgroundPosition() ;
}
}
function moveMask(x,y , parent){
var rect = parent.getBoundingClientRect() ;
mask.style.left = x - rect.x - mask.offsetWidth / 2 + "px" ;
mask.style.top = y - rect.y - mask.offsetHeight / 2 + "px" ;
if(mask.offsetLeft <= 0) mask.style.left = 0 ;
if(mask.offsetTop <= 0) mask.style.top = 0 ;
if(mask.offsetLeft >= parent.clientWidth - mask.clientWidth){
mask.style.left = parent.clientWidth - mask.clientWidth + "px" ;
}
if(mask.offsetTop >= parent.clientHeight - mask.clientHeight){
mask.style.top = parent.clientHeight - mask.clientHeight + "px" ;
}
}
function zoomBackgroundPosition(){
var scale = ZOOM_WIDTH / MASK_WIDTH ;
zoom.style.backgroundPositionX = -mask.offsetLeft * scale + "px" ;
zoom.style.backgroundPositionY = -mask.offsetTop *scale + "px" ;
}