我一直在使用jQuery開發一個項目,其中我有一個div元素,上面寫着「click」,當您嘗試點擊它時,它會移動到窗口內的隨機位置。我遇到的問題是,每隔一段時間,div將只移動一點點,將光標留在div內,允許用戶點擊鏈接。如何讓我的div元素移動超過200px?
我是相當新的JavaScript,我不太確定我應該如何去做這樣的事情。
我在想我可以做一些事情,比如從舊的位置減去新的位置,並檢查它們是否有小於200px的差異,如果他們這樣做,重新計算數字。如果這不符合你的要求,我完全接受其他方法。
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>
你的建議的解決方案聽起來足夠直截了當給我。如果我是你,我會嘗試。 – dave