js+css实现一个逃避躲避你点击的按钮代码

代码语言:html

所属分类:其他

代码描述:js+css实现一个逃避躲避你点击的按钮代码

代码标签: js css 逃避 躲避 点击 按钮 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  

  
  
  
<style>
#escape-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 1em 2em;
  font-size: 20px;
  background-color: #7e2cdb;
  color: white;
  border: none;
  border-radius: 6px;
  font-family: 'IBM Plex Sans';
  box-sizing: border-box;
}
</style>


  
</head>

<body>
  <button id="escape-button">Click here</button>

  
      <script  >
var button = document.getElementById("escape-button");
var proximity = 200;
var isButtonMoving = false;

function moveButton() {
  if (isButtonMoving) {
    return;
  }

  var viewportWidth = window.innerWidth;
  var viewportHeight = window.innerHeight;
  var buttonWidth = button.offsetWidth;
  var buttonHeight = button.offsetHeight;

  var currentX = parseInt(button.style.left) || 0;
  var currentY = parseInt(button.style.top) || 0;

  var randomX, randomY;
  var minDistance = proximity + 50;

  do {
    randomX = Math.floor(Math.random() * (viewportWidth - buttonWidth));
    randomY = Math.floor(Math.random() * (viewportHeight - buttonHeight));
  } while (calculateDistance(currentX, currentY, randomX, randomY) < minDistance);

  if (randomX + buttonWidth > viewportWidth) {
    randomX = viewportWidth - buttonWidth;
  }
  if (randomY + buttonHeight > viewportHeight) {
    randomY = viewportHeight - buttonHeight;
  }

  button.style.transition = "left 0.5s, top 0.5s";
  button.style.left = randomX + "px";
  button.style.top = randomY + "px";

  isButtonMoving = true;

  button.addEventList.........完整代码请登录后点击上方下载按钮下载查看

网友评论0