给这个图片添加摄像头图标,并获取图标的坐标值,也就是图标的css样式是positon:absolute,获取left和top的值。
思路是这样的,获取这里的长度,
1.鼠标点击时距浏览器的左边距离和上边距离,相当于(0,0)坐标
let x = e.clientX;
let y = e.clientY;
2.图片距浏览器顶部的距离
let imgTop = $('.imageBox img').offset().top;
let imgLeft = $('.imageBox img').offset().left;
3.就能获取到图片2中箭头的距离,即鼠标点击的位置距背景图顶部的距离
let cursorTop = y - imgTop;
let cursorLeft = x - imgLeft;
4.计算得出图标的left和top值,这里是%。
let width = $('.imageBox img').width();
let height = $('.imageBox img').height();
let left = (cursorLeft/width*100).toFixed(2)
let top = (cursorTop/height*100).toFixed(2)
5.效果如下图,但是鼠标点击处是图标的左上角,感觉好像是差一点
6.应该让鼠标点击处是图标的中心,就需要获取图标中心的坐标,然后 减去图片2中箭头的距离。
//设置添加的小图标的center为中心点
let pointLeft = $('.imageBox .block').width()*0.5;
let pointTop = $('.imageBox .block').height()*0.5;
//鼠标点击无差距
let xData = cursorLeft - pointLeft;
let yData = cursorTop - pointTop;
7. 完整代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.imageBox{
width: 800px;
position: relative;
overflow: hidden;
margin: 5% 2%;
}
.imageBox img{
width: 100%;
height: 100%;
}
.imageBox .block{
width: 3%;
height: 4%;
background: url(camera.png) 0 0 no-repeat;
background-size: 100% 100%;
position: absolute;
}
</style>
</head>
<body>
<div class="page">
<div class="imageBox">
<img src="https://img0.baidu.com/it/u=3593454291,2854711423&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=500" >
<div class="block">
</div>
</div>
</div>
<script src="jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$('.imageBox').click(function(e){
//鼠标点击时距浏览器的左边距离和上边距离,相当于(0,0)坐标
let x = e.clientX;
let y = e.clientY;
//图片的宽高
let width = $('.imageBox img').width();
let height = $('.imageBox img').height();
//图片距浏览器顶部的距离
let imgTop = $('.imageBox img').offset().top;
let imgLeft = $('.imageBox img').offset().left;
//鼠标点击的位置距背景图顶部的距离
let cursorTop = y - imgTop;
let cursorLeft = x - imgLeft;
//设置添加的小图标的center为中心点
let pointLeft = $('.imageBox .block').width()*0.5;
let pointTop = $('.imageBox .block').height()*0.5;
//鼠标点击无差距
let xData = cursorLeft - pointLeft;
let yData = cursorTop - pointTop;
let left = (xData/width*100).toFixed(2)
let top = (yData/height*100).toFixed(2)
console.log(x);
console.log(y);
// let html = `<div class="block" style="top: ${top}%;left: ${left}%;"></div>`
// $('.imageBox').append(html);
$('.imageBox .block').css({'top':top+'%'})
$('.imageBox .block').css({'left':left+'%'})
})
</script>
</body>
</html>