写了一个鼠标放到图片上,局部图片放大的例子(放大镜)。
以前想写这个功能,但是不会,百度一圈找到了几个例子却被嵌入了很多废代码,所以很生气,现在我把它晒出来这是html代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.
<html xmlns="http://www.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>放大镜</title>
<script src="js/js.js" type="text/javascript"></script>
</head>
<body>
<style type="text/css">
#box_1 {height:400px; width:400px; border:3px #F00 solid; position:relative; float:left; margin-left:200px;}
#box_2 {height:100px; width:100px; background- color: #F90; margin:auto; position:absolute; filter:alpha(opacity=30); /*IE 滤镜,透明度50%*/
-moz-opacity:0.3; /*Firefox私有,透明度50%*/
opacity:0.3;/*其他,透明度50%*/ display:none;}
#box_3 {height:300px; width:300px; border:3px #F00 solid; float:left; margin-left:20px; overflow:hidden; position:relative; display:none;}
#img {margin:auto; position:absolute; }
.cl { clear:both;}
</style>
<div id="box_1">
<img src="images/js5.png" />
<div id="box_2" >
</div>
</div>
<div id="box_3">
<img src="images/js5a.png" id="img"/>
</div>
<div class="cl"></div>
</body>
</html>
这是js代码:
window.onload = function(){
var box_1 = document.getElementById("box_1");
var box_2 = document.getElementById("box_2");
var box_3 = document.getElementById("box_3");
var img = document.getElementById("img");
box_1.onmousemove = move;
box_1.onmouseout = dis;
box_1.onmouseover = show;
}
function move(e){
box_2.style.display = "block";
var x = e.clientX;
var y = e.clientY;
var bl = box_1.offsetLeft;
var bt = box_1.offsetTop;
var postion_x = x - bl - 50;
var postion_y = y - bt - 50;
box_2.style.top = postion_y + "px";
box_2.style.left = postion_x + "px";
img.style.left = -postion_x*3 + "px";
img.style.top = -postion_y*3 + "px";
if(postion_x >= 300){
box_2.style.left = 300 + "px";
img.style.left = -900 + "px";
}
if(postion_y >= 300){
box_2.style.top = 300 + "px";
img.style.top = -900 + "px";
}
if(postion_x <= 0){
box_2.style.left = 0 + "px";
img.style.left = 0 + "px";
}
if(postion_y <= 0){
box_2.style.top = 0 + "px";
img.style.top = 0 + "px";
}
document.title = postion_x + " " + postion_y;
}
function dis(){
box_2.style.display = "none"
box_3.style.display = "none";
}
function show(){
box_2.style.display = "block";
box_3.style.display = "block";
}