javascript - 当我将鼠标放在 JavaScript 上时,我需要重新定位方块。我怎么做?
问题描述
A.在“init”函数中添加“reposition”函数所需的代码,只要将鼠标悬停在与 CSS 类“square”关联的页面元素上,就会调用该代码。B.修改“重新定位”功能,使其允许您重新定位正方形相对于对角线对称。为此,只需颠倒该正方形的水平和垂直位置即可。注意:粉色方块不会移动,因为它正好在对角线上(水平和垂直位置相同)。
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Reposition the squares</title>
<style>
#bac {
position: relative;
width: 400px;
height: 400px;
border: 1px solid red;
text-align: center;
}
.square {
width: 50px;
height: 50px;
}
#square1 {
position: absolute;
left: 300px;
top: 200px;
background-color: red;
}
#square2 {
position: absolute;
left: 120px;
top: 75px;
background-color: blue;
}
#square3 {
position: absolute;
left: 50px;
top: 240px;
background-color: orange;
}
#square4 {
position: absolute;
left: 350px;
top: 0px;
background-color: black;
}
#square5 {
position: absolute;
left: 50px;
top: 50px;
background-color: pink;
}
</style>
<script>
function init() {
//Code here
}
function reposition() {
//code here
}
</script>
</head>
<body onload="init()">
<h1>Reposition the squares</h1>
<div id="bac">
<div id="square1" class="square"></div>
<div id="square2" class="square"></div>
<div id="square3" class="square"></div>
<div id="square4" class="square"></div>
<div id="square5" class="square"></div>
</div>
</body>
</html>
解决方案
你可以使用这个脚本
<script>
const squares = document.querySelectorAll(".square");
for(let i = 0; i < squares.length; i++){
squares[i].addEventListener("mouseover",(e)=>{
let v = getComputedStyle(squares[i]);
let top = v.getPropertyValue('top').replace(/\D/g, "");
let left = v.getPropertyValue('left').replace(/\D/g, "");;
if(top == left){
e.preventDefault();
}
else{
squares[i].style.top = left+"px";
}
})
}
</script>
首先我打电话给所有的方格,然后我为每个方格制作了一个事件
其次,当我将鼠标放在其上时,我搜索了顶部和左侧属性
第三,我只从没有“px”的属性中得到数字,这就是我使用正则表达式的原因
最后,我为每个不匹配的正方形给出了相同的顶部和左侧值
也许有人可以给你一个简短的代码,但这是我的解决方案(我还是学生),它对我有用。
注意:橙色方块将隐藏在粉红色方块下方,因为两者的顶部和左侧值相同。
推荐阅读
- discord - (discord.js) 删除任何包含正则表达式的消息的不和谐机器人
- python - 如何在上下文中运行协程?
- javascript - 使用 Jest 测试 Redis 功能
- javascript - 如何通过Javascript以编程方式模拟打开选择文件对话框?
- java - 如果Java程序应该连续接收来自串行通讯的数据,但现在遇到程序延迟或滞后怎么办?
- php - IE 不在多个子域中保留 cookie
- react-native - @react-native-community/datetimepicker 不适用于 ios 14
- c# - 我正在尝试使用 c# winforms 应用程序列出 ftp 服务器中存在的所有文件
- android - 如何从 MutableLiveData 中获取元素
- r - data.frame 每一行中最大数字的列名