JS獲取滑鼠點選圖片時點選點所在圖片的寬高的百分比
阿新 • • 發佈:2019-01-31
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
html,
body {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<input id="xxx" type="text" /><input id="yyy" type="text" />
<img id="imageid" src="img/beijing.png" onclick="Show(this)"/>
</body>
</html>
<script>
var naturalWidth = document.getElementById('imageid').naturalWidth,
naturalHeight = document.getElementById('imageid').naturalHeight;
console.log(naturalWidth);
console.log(naturalHeight);
function mousePosition(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
function mouseMove(ev){
ev = ev || window.event;
var mousePos = mousePosition(ev);
document.getElementById('xxx').value = mousePos.x;
document.getElementById('yyy').value = mousePos.y;
}
document.onmousemove = mouseMove;
function Show(el){
var x = parseInt(document.getElementById('xxx').value)-el.offsetLeft;
var y = parseInt(document.getElementById('yyy').value)-el.offsetTop;
x = "X:"+x/naturalWidth*100+"%";
y = "Y:"+y/naturalHeight*100+"%";
alert(x+","+y);
}
</script>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
html,
body {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<input id="xxx" type="text" /><input id="yyy" type="text" />
<img id="imageid" src="img/beijing.png" onclick="Show(this)"/>
</body>
</html>
<script>
var naturalWidth = document.getElementById('imageid').naturalWidth,
naturalHeight = document.getElementById('imageid').naturalHeight;
console.log(naturalWidth);
console.log(naturalHeight);
function mousePosition(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
}
function mouseMove(ev){
ev = ev || window.event;
var mousePos = mousePosition(ev);
document.getElementById('xxx').value = mousePos.x;
document.getElementById('yyy').value = mousePos.y;
}
document.onmousemove = mouseMove;
function Show(el){
var x = parseInt(document.getElementById('xxx').value)-el.offsetLeft;
var y = parseInt(document.getElementById('yyy').value)-el.offsetTop;
x = "X:"+x/naturalWidth*100+"%";
y = "Y:"+y/naturalHeight*100+"%";
alert(x+","+y);
}
</script>