我试着实现这个问题,如果我点击点击按钮,箭头会移动,接触到圆圈,并改变圆圈的颜色。
我试着用CSS关键帧和JavaScript来实现它,但这不起作用。我对关键帧和javascript没有任何概念。我是JavaScript新手。
function hit() {
var circle = document.getElementById('circle');
var arrow = document.getElementById('arrow');
// Calculate the distance between the arrow and the circle's center
var arrowPos = arrow.getBoundingClientRect();
var circlePos = circle.getBoundingClientRect();
var distance = Math.sqrt(Math.pow(arrowPos.left - circlePos.left, 2) + Math.pow(arrowPos.top - circlePos.top, 2));
// If the distance is less than or equal to the sum of the arrow's width and half of the circle's width, they are touching
if (distance <= arrow.offsetWidth + circle.offsetWidth / 2) {
circle.style.backgroundColor = 'green';
}
}
function reset() {
var circle = document.getElementById('circle');
circle.style.backgroundColor = 'blue';
}
.container {
border: 3px solid black;
height: 60vh;
width: 90vh;
margin: auto;
display: flex;
justify-content: space-between;
align-items: center;
}
h1 {
text-align: center;
}
.circle {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: blue;
margin-left: 12px;
}
.icon-arrow {
width: 90px;
height: 3px;
background-color: black;
border-radius: 2px;
position: relative;
margin-right: 12px;
animation-name: icon;
animation-duration: 5s;
}
.icon-arrow:after {
content: '';
display: inline-block;
width: 30px;
height: 2px;
background-color: black;
transform: rotate(45deg);
position: absolute;
left: -5px;
top: 11px;
}
.icon-arrow:before {
content: '';
display: inline-block;
width: 30px;
height: 2px;
background-color: black;
transform: rotate(-45deg);
position: absolute;
right: 65px;
bottom: 9px;
}
.button {
float: right;
margin-right: 260px;
padding-top: 9px;
width: 20%;
border-radius: 3px;
}
.button button {
width: 20%;
color: white;
background-color: grey;
margin-right: 16px
}
@keyframes icon {
10% {
top: 0px;
left: 0px;
}
}
<body>
<h1>Bubble App</h1>
<section class="container">
<div class="circle"></div>
<div class="icon-arrow"></div>
</section>
<div class="button" role="button">
<button onclick="hit()">Hit</button>
<button onclick="reset()">Reset</button><br>
</div>
</body>
1条答案
按热度按时间cx6n0qe31#
下面是一个使用
offset
的示例