js点击获取—通过JS获取图片的绝对对坐标位置

时间:2022-10-17 15:38:10

一、通过JS获取鼠标点击时图片的相对坐标位置

源代码如下所示: 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
.wrap{
width:300px;
height: 200px;
background: #ccc;
position: relative;
}
.ball{
width:20px;
height: 20px;
background: red;
border-radius: 50%;
position: absolute;
}
.box {
width: 400px;
height: 400px;
overflow: auto;
} </style>
</head>
<body>
<div class="box">
<div class="wrap">
<img src="data:images/test.jpg" alt="">
<div class="container"></div>
</div>
</div> <script src="js/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$('.wrap').click(function(e){
var radius=10;//半径
var offset=$(this).offset();
var top=e.pageY-offset.top-radius+"px";
var left=e.pageX-offset.left-radius+"px";
//$('.wrap').append('<div class="ball" style="top:'+top+';left:'+left+'"></div>');
$('.container').html('<div class="ball" style="top:'+top+';left:'+left+'"></div>');
alert(top+"_"+left);
})
</script>
</body>
</html>