javascript - 查找容器内的实时鼠标坐标
问题描述
因此,我涉足 JavaScript 坐标并创建了一个容器,其中鼠标的 x 和 y 坐标将显示在容器内。
该代码几乎可以正常工作,只是它仅在我进入容器时才显示坐标并且除非我重新进入容器才会更改。这是下面的代码: -
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>king crimson</title>
</head>
<body>
<style>
body{
display: flex;
align-items: center;
align-content: center;
}
.container{
width: 500px;
height: 400px;
background-color: crimson;
margin: auto;
color: white;
padding-top: 2rem;
text-align: center;
}
</style>
<div class="container"></div>
<!-- START JAVASCRIPT -->
<script>
const box = document.querySelector('.container');
box.addEventListener('mouseover', e =>{
let x = event.clientX;
let y = event.clientY;
const coords = `
Coordinate of x is ${x} and coordinate of y is ${y}
`
box.innerHTML = coords;
});
</script>
<!-- END JAVASCRIPT-->
</body>
</html>
解决方案
const box = document.querySelector('.container');
box.addEventListener('mousemove', e =>{
let x = event.clientX;
let y = event.clientY;
const coords = `
Coordinate of x is ${x} and coordinate of y is ${y}
`;
box.innerHTML = coords;
});
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>king crimson</title>
</head>
<body>
<style>
body{
display: flex;
align-items: center;
align-content: center;
}
.container{
width: 500px;
height: 400px;
background-color: crimson;
margin: auto;
color: white;
padding-top: 2rem;
text-align: center;
}
</style>
<div class="container"></div>
<!-- END JAVASCRIPT-->
</body>
</html>
推荐阅读
- python - python - 如何使用pandas和/或plotly在Python中每x行创建新表?
- c - execl 找不到 vim
- javascript - 滚动时到达不同的div元素后如何更改导航图像
- c# - 检查文本框中的否定输入
- wordpress - 如何根据 woocommerce 中的订单总数更改电子邮件发件人?
- javascript - 如何将嵌套对象“解包”为数组?
- python - 使用 ansible-runner 作为 Python 模块接口到 Ansible 错误:RunnerConfig' 对象没有属性 'command'
- arrays - Python函数有一个新的数组
- docker - 无法在 snap docker 19.03 中启用实验性
- typescript - Jest Matcher 错误:收到的值必须是承诺或返回承诺的函数