我一直在使用 jQuery 开发一个元素,其中有一个显示“单击”的 div 元素,当您尝试单击它时,它会移动到窗口内的随机位置。我遇到的问题是,每隔一段时间 div 只会移动一点点,将光标留在 div 内,从而允许用户单击链接。
我是 javascript 的新手,我不太确定我应该如何做这样的事情。
我想我可以做一些事情,比如从旧位置中减去新位置并检查它们的差异是否小于 200 像素,如果是,则重新计算数字。如果这不是您的做法,我完全愿意接受其他方法。
function setPosition() {
var randY = Math.floor(Math.random() * (window.innerHeight - 200));
var randX = Math.floor(Math.random() * (window.innerWidth - 200));
$('#square').animate({
top: randY + 'px',
left: randX + 'px'
}, 200);
}
$(document).ready(function() {
setPosition()
var tries = 0;
//tries is just to stop it after it reaches 1000.
//I'm planning to make some kind of page to congradulate you on wasting your time.
$('#square').mouseenter(function() {
if (tries < 1000) {
setPosition();
tries += 1;
console.log(tries)
}
});
});
#square {
background: orange;
height: 115px;
width: 150px;
position: relative;
text-align: center;
padding-top: 35px;
}
h3,
h3 * {
font-family: "Comic Sans MS", cursive, sans-serif;
font-size: 20px;
vertical-align: middle;
position: relative;
color: black;
text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<link rel=stylesheet type=text/css href=square.css>
<script src=jquery-1.11.3.min.js></script>
<script src=square.js></script>
</head>
<body>
<div id=square>
<h3><a href=''>Click</a></h3>
</div>
</body>
</html>
最佳答案
我认为您可能想要运行随机化逻辑,直到它找到距离当前位置超过 200 像素的组合。
在我的脑海中,那会是这样的:
function setPosition() {
var $square = $('#square');
var prevY = $square.offset().top;
var prevX = $square.offset().left;
var randY, randX;
do {
randY = Math.floor(Math.random() * (window.innerHeight - 200));
randX = Math.floor(Math.random() * (window.innerWidth - 200));
} while( Math.abs(randY - prevY) < 200 || Math.abs(randX - prevX) < 200 );
$square.animate({
top: randY + 'px',
left: randX + 'px'
}, 200);
}
关于javascript - 如何让我的 div 元素移动超过 200px?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34048597/