放大镜

HTML

<div id="box">
	<img id="small_img" src="http://a.hiphotos.bdimg.com/album/h%3D370%3Bq%3D90/sign=bc1409f23a292df588c3aa128c0a2d5d/4d086e061d950a7b2af282190ad162d9f3d3c92c.jpg" />
	<span id="small_block"></span>
</div>
<div id="big_block">
	<img id="big_img" src="http://a.hiphotos.bdimg.com/album/h%3D370%3Bq%3D90/sign=bc1409f23a292df588c3aa128c0a2d5d/4d086e061d950a7b2af282190ad162d9f3d3c92c.jpg" />
</div>

CSS

*{
	margin:0;
	padding:0
}
#box{
	width:277px;
	height:185px;
}
#small_img{
	width:100%;
	height:100%;
}
#small_block{
	width:75px;
	height:75px;
	position:absolute;
	left:0;
	top:0;
	opacity:0.3;
	fliter:alpha(opacity=30);
	background-color:blue;
	border:1px solid #000;
	display:none;
}

#big_block{
	width:150px;
	height:150px;
	overflow:hidden;
	position:absolute;
	left:300px;
	top:20px;
	display:none;
}
#big_img{
	width:554px;
	height:370px;
	position:absolute;
}
/* 大图和小图的比例是2:1,大块和小块的比例也是2:1 */

JavaScript

/**
  图片竟然没有显示出来,不过也不影响效果了
**/

window.onload=function() {

    /* 
    * 这个地方用 box 代替小图片,因为它们宽高相等,并且给图片加鼠标事件有问题:
    * 会不断触发鼠标的 mouseover 和 mouseout 事件。
    * 至于为什么会这样,还不是很明白,求解????????????
    */
	var smallImg = getid("box"),  
		smallBlock = getid("small_block"),
		bigImg = getid("big_img"),
		bigBlock = getid("big_block");
	
	// offset 这种属性取值的时候,元素必须是可见的,所以把取值放到下面了;
    // 变量太多容易乱,可以用对象处理。
	var smallImgWidth, smallImgHeight, 
        smallBlockHeight, smallBlockWidth,
        bigBlockHeight, bigBlockWidth,
		bigImgHeight, bigImgWidth;
	
	// 鼠标移入原图时,内部选块区域和右侧放大区域显示;离开时,隐藏
	smallImg.onmouseover = function(ev){
		smallBlock.style.display = "block";
		bigBlock.style.display = "block";
		setValue && setValue();
	};

	smallImg.onmouseout = function(ev){
		smallBlock.style.display = "none";
		bigBlock.style.display = "none";
	};

	// 获取下面所需的数据,这些数据是死的,取一次就可以
	function setValue(){
		smallImgWidth = smallImg.offsetWidth,
		smallImgHeight = smallImg.offsetHeight,
		smallBlockHeight = smallBlock.offsetHeight,
		smallBlockWidth = smallBlock.offsetWidth,
		bigBlockHeight = bigBlock.offsetHeight,
		bigBlockWidth = bigBlock.offsetWidth,
		bigImgHeight = bigImg.offsetHeight,
		bigImgWidth = bigImg.offsetWidth;
		setValue = null;
	}

	// 鼠标在原图上移动,换算比例,显示大图
	smallImg.onmousemove = function(ev){

		var oEvent = ev || event;
		var l = oEvent.clientX - this.offsetLeft - smallBlockWidth / 2;
		var t = oEvent.clientY - this.offsetTop - smallBlockHeight / 2;

		var rangeWidth = smallImgWidth - smallBlockWidth,
			rangeHeight = smallImgHeight - smallBlockHeight;
		
		// 范围限制
		l = l < 0 ? 0 : l;
		l = l > rangeWidth ? rangeWidth : l;
		t = t < 0 ? 0 : t;
		t = t > rangeHeight ? rangeHeight : t;
		
		smallBlock.style.left = l + "px";
		smallBlock.style.top = t + "px";

		// 求比例,显示大图
		var bw = l / smallImgWidth;
		bigImg.style.left = -bigImgWidth * bw + "px";

		var bh = t / smallImgHeight;
		bigImg.style.top = -bigImgHeight * bh + "px";
	}
};

function getid(id){
	return...