js 鼠标事件实现放大镜效果

<div id="left">
	<div id="inner">div>
	<img src="1.jpg">
div>
<div id="right">
	<img src="1.jpg">
div>

这里就直接写构造函数部分

function Change(){
	this.oLeft = document.getElementById("left");
    this.oLeftImg = this.oLeft.getElementsByTagName("img")[0];
    this.oInner = document.getElementById("inner");
    this.oRight = document.getElementById("right");
    this.oRightImg = this.oRight.getElementsByTagName("img")[0];
    console.log(this.oLeft,this.oLeftImg,this.oInner,this.oRight,this.oRightImg);
}
Change.prototype.toChange=function(){
	//使用箭头函数方便this的指向
	this.oLeft.onmouseover=()=>{
		this.oInner.style.display = "block";
		this.oRight.style.display = "block";
	}
	this.oLeft.onmouseout=()=>{
        this.oInner.style.display = "none";
        this.oRight.style.display = "none";
    }
    //这里需要某些属性 需要获取事件对象
    this.oLeft.onmousemove = (e)=>{
    	//限制出界
		this.w = this.oLeft.offsetWidth  - this.oInner.offsetWidth; 
		this.h = this.oLeft.offsetHeight - this.oInner.offsetHeight;
		var evt = e || event;
		var x = evt.pageX - this.oLeft.offsetLeft;
		var y = evt.pagey - this.oLeft.offsetTop;
		var l = x-oInner.offsetWidth/2;
		var t = y-oInner.offsetHeight/2;
		//判断
		l =l <=0?0:l>=this.w?this.w:l;
		t =t <=0?0:t>=this.h?this.h:t;
		//inner的变化
		this.oInner.style.left = l+"px";
    	this.oInner.style.top = t+"px";
    	//右边大图的变化
    	this.oRightImg.style.left = -l*(this.oRightImg.offsetWidth/this.oLeft.offsetWidth)+"px";
    	this.oRightImg.style.top  = -t*(this.oRightImg.offsetWidth/this.oLeft.offsetWidth)+"px";
	}

}

你可能感兴趣的:(js 鼠标事件实现放大镜效果)