效果圖如下:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
text-align: center;
}
div img{
width: 200px;
height: 200px;
margin-right: 20px;
cursor: pointer;
}
.bigBox{
width: 400px;
height: 400px;
position: absolute;
display: none;
}
.bigBox img{
width: 100%;
height: 100%;
}
</style>
<script type="text/javascript">
window.onload=function(){
function get(){
if(arguments.length==1){
return document.getElementById(arguments[0]);
}else{
return arguments[0].getElementsByTagName(arguments[1]);
}
}
var box=get(document,"div")[0],
imgs=get(box,"img"),
bigBox=get("bigBox"),
i=0;
for(i=0;i<imgs.length;i++){
//鼠標移到相應的圖片觸發
imgs[i].onmouseover=function(){
var big=document.createElement("img");
var big=new Image();
big.src=this.src;
bigBox.appendChild(big);
bigBox.style.display="block";
this.style.opacity="0.6";
};
//鼠標移動,改變座標,這裏大圖的座標相比鼠標的座標要偏移20像素,如果大圖座標直接與鼠標座標相等,很容易重複觸發onmouseover事件,從而不斷的添加big節點
imgs[i].onmousemove=function(event){
var event=event || window.event;
marginRight=box.offsetWidth-event.clientX-20;
//當大圖到達瀏覽器窗口右邊界時改爲左側顯示
bigBox.style.left=bigBox.offsetWidth>marginRight?event.clientX-20-bigBox.offsetWidth+"px":event.clientX+20+"px";
bigBox.style.top=event.clientY+20+"px";
};
//鼠標移出,清除大圖節點
imgs[i].onmouseout=function(){
bigBox.style.display="none";
bigBox.removeChild(bigBox.lastChild);
this.style.opacity="";
};
}
};
</script>
</head>
<body>
<div>
<img src="../images/1.jpg">
<img src="../images/2.jpg">
<img src="../images/3.jpg">
<img src="../images/4.jpg">
</div>
<div class="bigBox" id="bigBox"></div>
</body>
</html>