[英]My “div” is moving from top to bottom (i.e 200px height from top) and fix on a top(starting postion). but I want to fix on a bottom.How can I do it?
[英]How can I make my div element move more than 200px?
我一直在使用jQuery开发一个项目,其中有一个div元素显示“ click”,当您尝试单击它时,它会移动到窗口内的随机位置。 我遇到的问题是,每隔一段时间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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.