js图片放大境效果

放大境效果如下图所示,当鼠标放到小图时,就会出现浅黄色的小块,而右边方框也出现了,并且右边方框的内容时根据浅黄色小块的内容变换而变换;

原理:

  1,准备2张图,一大一小,如上图所示,小图的盒子div1放小图,大图的盒子div2放大图,  div2一定要小于大图,假设oSapn在oDiv中距离左边的距离(L) ,即oSapn在oDiv中距离上边的距离(T) 

  2、计算浅黄色的小块(span)在小图中的移动比例,然后把比例赋给大图即可

    向左的移动比例为:   L / (div1.offsetWidth - span.offsetWidth)

    向上的移动比例为:  T / (div1.offsetHeight - span.offsetHeight)

注意:在div1中有一句<div id="mask"></div>,这个的大小与div1一样大,这是为了解决----子集事件影响父级事件的bug的

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>放大境效果</title>
    <style>
	#div1 {width: 200px;height: 200px;overflow: hidden;position: relative;}		
	#div1 span {width: 100px;height: 100px;background: yellow;opacity: 0.5;
		filter: alpha(opacity=50);position: absolute;left: 0;top: 0;display: none;
	}
	#div1 img{width: 100%;}	
	#mark {width: 200px;height: 200px;background: red;position: absolute;left: 0;top: 0;
		opacity: 0;filter: alpha(opacity=0);
	}		
	#div2 {width: 300px;height: 300px;position: absolute;left: 250px;top: 0px;overflow: hidden;}			
	#div2 img {position: absolute;left: 0;top: 0;width: 580px;height: 580px;}
    </style>
    <script type="text/javascript">
	window.onload = function() {
	    var oDiv = document.getElementById('div1');
	    var oSpan = oDiv.getElementsByTagName('span')[0];
	    var oDiv2 = document.getElementById("div2");
	    var img2 = oDiv2.getElementsByTagName("img")[0];

	    oDiv.onmouseover = function() {
		oSpan.style.display = "block";
		oDiv2.style.display = "block";
	   }
	   oDiv.onmouseout = function() {
		oSpan.style.display = "none";
		oDiv2.style.display="none";
	   }
	   oDiv.onmousemove = function() {
		var ev = ev || window.event;
		//默认情况在鼠标在oSpan的中心点,求出oSapn在oDiv中距离左边的距离与上边的距离
		var L = ev.clientX - oDiv.offsetLeft - oSpan.offsetWidth / 2;
		var T = ev.clientY - oDiv.offsetTop - oSpan.offsetHeight / 2;
					
		if(L < 0) {
			L = 0
		} else if(L > oDiv.offsetWidth - oSpan.offsetWidth) {
			L = oDiv.offsetWidth - oSpan.offsetWidth;
		}

		if(T < 0) {
			T = 0
		} else if(T > oDiv.offsetHeight - oSpan.offsetHeight) {
			T = oDiv.offsetHeight - oSpan.offsetHeight;
		}

		oSpan.style.left = L + 'px';
		oSpan.style.top = T + 'px';
		//移动比例
		var scaleX = L / (oDiv.offsetWidth - oSpan.offsetWidth);
		var scaleY = T / (oDiv.offsetHeight - oSpan.offsetHeight);
					
		//给负值是为了反方向移动
		img2.style.left = -scaleX * (img2.offsetWidth - oDiv2.offsetWidth) + "px";
		img2.style.top = -scaleY * (img2.offsetHeight - oDiv2.offsetHeight) + "px";
	    }
	}
    </script>
</head>

<body>
    <div id="div1">
	<img src="img/b2.jpg" />
	<span></span>
	<div id="mask"></div>
    </div>
    <div id="div2">
	<img src="img/b1.jpg" />
    </div>
</body>
</html>

 

posted @ 2017-04-01 09:29  梁小清  阅读(217)  评论(0编辑  收藏  举报