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

时间:2021-02-17 15:36:08

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

源代码如下所示:

 <!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>通过JS获取图片的相对坐标位置</title> <style>
body {margin: 0; padding: 0; }
#area{width:300px;height:300px;}
#area img{border:none;cursor:pointer;width: 300px;height: 300px;}
.testBox {
width: 200px;
height: 200px;
overflow: auto;
}
</style>
</head> <body id="">
<h3>通过JS获取图片的相对坐标位置 示例</h3>
<div class="testBox">
<div id="area" onclick="getClickPos(event);">
<img id='imageID' src="data:images/1.jpg">
</div>
</div> <script type="text/javascript">
function getClickPos(e){
var xPage = (navigator.appName == 'Netscape')? e.pageX : event.x+document.body.scrollLeft;
var yPage = (navigator.appName == 'Netscape')? e.pageY : event.y+document.body.scrollTop;
identifyImage = document.getElementById("imageID");
img_x = locationLeft(identifyImage);
img_y = locationTop(identifyImage);
var xPos = xPage-img_x;
var yPos = yPage-img_y;
alert('X : ' + xPos + '\n' + 'Y : ' + yPos);
}
//找到元素的屏幕位置
function locationLeft(element){
offsetTotal = element.offsetLeft;
scrollTotal = 0; //element.scrollLeft but we dont want to deal with scrolling - already in page coords
if (element.tagName != "BODY"){
if (element.offsetParent != null)
return offsetTotal+scrollTotal+locationLeft(element.offsetParent);
}
return offsetTotal+scrollTotal;
}
//find the screen location of an element
function locationTop(element){
offsetTotal = element.offsetTop;
scrollTotal = 0; //element.scrollTop but we dont want to deal with scrolling - already in page coords
if (element.tagName != "BODY"){
if (element.offsetParent != null)
return offsetTotal+scrollTotal+locationTop(element.offsetParent);
}
return offsetTotal+scrollTotal;
}
</script>
</body>

补充

二、js图片上标注热点(相对定位)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<style>
.wrap{
width:200px;
height: 200px;
overflow: auto;
background: #ccc;
position: relative;
}
.ball{
width:20px;
height: 20px;
background: red;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<div class="wrap">
<img src="data:images/1.jpg" alt="">
</div>
<script>
$('.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";
console.log(top);
console.log(left);
$('.wrap').append('<div class="ball" style="top:'+top+';left:'+left+'"></div>')
})
</script>
</body>
</html>