不能将html用于此目的。我坚持这一点:双击一个正方形时,将发生以下情况:
如果正方形的id是偶数:单击的正方形后的正方形应从页面中删除如果单击的正方形后面没有正方形,则显示警告,指示如果正方形的id为奇数:应从页面中删除单击的正方形之前的正方形如果单击的正方形之前没有一个正方形,则显示警告,表明是
这是我的Javascript:
document.addEventListener("DOMContentLoaded", function () {
let button = document.createElement('button');
let btnText = document.createTextNode('Add Square');
button.appendChild(btnText);
document.body.appendChild(button);
let sqContainer = document.createElement('div');
sqContainer.classList.add('container')
document.body.appendChild(sqContainer)
let num = 0
button.addEventListener("click", function () {
let square = document.createElement('div')
square.classList.add('square')
sqContainer.appendChild(square)
document.body.appendChild(sqContainer)
num++
square.setAttribute('id', num)
let idDisplay = document.createElement('span')
idDisplay.classList.add('id-display')
idDisplay.innerText = num
var colors = ["#85e6c5", "#51b9c6", "#6087c6", "#4d59ae", "#401a8e"];
square.addEventListener("click", function (e) {
e.target.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
})
if (num % 2 == 0) {
square.addEventListener("dblclick", function (e) {
square.remove();
})
}
// else {
// e.target.textContent = "O"
//
// }
})
})
和我的CSS
.container {
display: flex;
flex-wrap: wrap;
}
.square {
display: flex;
justify-content: center;
align-items: center;
height: 100px;
width: 100px;
margin-right: 10px;
margin-top: 10px;
background-color: black;
}
.square:before {
content: attr(id);
opacity: 0;
transition: opacity .25s ease;
color:white
}
.square:hover:before {
opacity: 1
}
您可以使用nextElementSibling获得与单击的元素对应的下一个元素:
let firstDiv = document.getElementById("firstDiv");
firstDiv.addEventListener('click', function()
{
secondDiv = this.nextElementSibling;
console.log(secondDiv.textContent);
});
div{ border: solid 1px black; margin-bottom: 10px;}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p>Below are two div boxes, click the first div to console.log the 2nd div's text content:</p>
<div id="firstDiv">First Div's Content</div>
<div>Second Div's Content</div>
</body>
</html>