JavaScript 实现红点弹跳动画:边框反弹、鼠标悬停暂停
<!DOCTYPE html>
<html>
<head>
<title>JavaScript 实现红点弹跳动画</title>
<style>
#div1 {
position: absolute;
top: 0;
left: 0;
width: 20px;
height: 20px;
background-color: #ccc;
cursor: pointer;
}
#div2 {
position: absolute;
top: 50%;
left: 50%;
margin-top: -15px;
margin-left: -50px;
width: 100px;
height: 30px;
background-color: red;
border-radius: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<div id='div1' onclick='closeDiv1()'></div>
<div id='div2' onmouseover='stopAnimation()' onmouseout='startAnimation()'></div>
<script>
var div2 = document.getElementById('div2');
var timer;
<pre><code> function startAnimation() {
timer = setInterval(function() {
var top = div2.offsetTop;
var left = div2.offsetLeft;
var width = div2.offsetWidth;
var height = div2.offsetHeight;
var clientWidth = document.documentElement.clientWidth;
var clientHeight = document.documentElement.clientHeight;
if (left <= 0 || left >= clientWidth - width) {
div2.style.left = left <= 0 ? 0 : clientWidth - width + 'px';
}
else {
div2.style.left = left + 5 + 'px';
}
if (top <= 0 || top >= clientHeight - height) {
div2.style.top = top <= 0 ? 0 : clientHeight - height + 'px';
}
else {
div2.style.top = top + 5 + 'px';
}
}, 10);
}
function stopAnimation() {
clearInterval(timer);
}
function closeDiv1() {
document.body.removeChild(document.getElementById('div1'));
}
startAnimation();
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/mDdC 著作权归作者所有。请勿转载和采集!