js div随鼠标移动,css图片放大镜效果
css代码:
index.css文件
/*
CSS样式
*/
body{ margin:30px;}
div {
cursor: pointer; /*鼠标:移动形状*/
width: 420px; /*宽*/
height: 420px; /*像素为单位*/
outline: 10px #0C3 solid;/*轮廓线-html5新增,老浏览器不一定支持*/
}
/*大图*/
#bgmj {
width: 220px;
height: 220px;
border: 10px blue solid; /*边框5像素*/
position: absolute; /*定位:绝对定位*/
top: 20px;
left:480px;
background-image:url(../img/12.jpg);
display:none;
}
#famj {
width: 220px;
height: 220px;
border: 10px blue solid; /*边框5像素*/
position: absolute; /*定位:绝对定位*/
top: 20px;
left:480px;
background-image:url(../img/22.jpg);
display:none;
}
html代码:
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>淘宝放大镜效果</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body>
<!--html注释-->
<h1 id="show">显示鼠标坐标:</h1>
<div id="box" style="float:left">
<img src="img/11.jpg" width="420">
</div>
<div id="fd" style="float:right; margin-right:200px">
<img src="img/21.jpg" width="500">
</div>
<section id="bgmj"></section>
<section id="famj"></section>
<script>
var box = document.getElementById("box");
var bgmj = document.getElementById("bgmj");
/*onmousemove 事件会在鼠标指针移动时发生*/
box.onmousemove = function(ev){
var x1 = ev.clientX - 30;
var y1 = ev.clientY - 30;
var w = 420;
var h = 620;
var px = 100*x1/w ;
var py = 100*y1/h;
show.innerHTML = 'X:' + px + ' Y:'+ py;
var str = px+"%" + " " + py+"%" ;
bgmj.style.display = "block";
bgmj.style.backgroundPosition = ""+str+"";
bgmj.style.top = ev.clientY+20+"px";
bgmj.style.left = ev.clientX+20+"px";
}
/*onmouseout 事件会在鼠标指针移出指定的对象时发生。*/
box.onmouseout = function() {
document.getElementById('bgmj').style.display = "none"
}
var fd = document.getElementById("fd");
var famg = document.getElementById("famj");
/*onmousemove 事件会在鼠标指针移动时发生*/
fd.onmousemove = function(ev)
{
var x1 = ev.clientX - 30;
var y1 = ev.clientY - 30;
var w = 500;
var h = 1030;
var px = 100*x1/w ;
var py = 100*y1/h;
show.innerHTML = 'X:' + px + ' Y:'+ py;
var str = px+"%" + " " + py+"%" ;
famg.style.display = "block";
famg.style.backgroundPosition = ""+str+"";
famg.style.top = ev.clientY+20+"px";
famg.style.left = ev.clientX+20+"px";
}
</script>
</body>
</html>
ev|| window.event.clientX 获取鼠标横向坐标
ev|| window.event.clientY 获取鼠标纵向坐标
famg.style.top 给对象的纵向坐标赋值
famg.style.left 给对象的横向坐标赋值
注意:在给坐标赋值的时候,一定要加长度单位如:px、em、pt、pc和%等,不然div不会跟着鼠标移动