大佬教程收集整理的这篇文章主要介绍了jquery – 固定容器中的随机运动,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
$(document).ready(function(){ animateDiv(); }); function makeNewPosition(){ // Get viewport dimensions (remove the dimension of the div) var h = $(window).height() - 50; var w = $(window).width() - 50; var nh = Math.floor(Math.random() * h); var nw = Math.floor(Math.random() * w); return [nh,nw]; } function animateDiv(){ var newq = makeNewPosition(); var oldq = $('.a').offset(); var speed = calcSpeed([oldq.top,oldq.left],newq); $('.a').animate({ top: newq[0],left: newq[1] },speed,function(){ animateDiv(); }); }; function calcSpeed(prev,next) { var x = Math.abs(prev[1] - next[1]); var y = Math.abs(prev[0] - next[0]); var greatest = x > y ? x : y; var speedModifier = 0.1; var speed = Math.ceil(greatest/speedModifier); return speed; }
CSS:
div.a { width: 50px; height:50px; BACkground-color:red; position:fixed; }
但是,我不相信上面的代码完全反对.我需要我的物体随机移动到一个容器内,现在可以说…宽度为1200像素,高度为500像素.
有人能引导我朝着正确的方向前进吗?我是编码的新手,所以我很难找到自己的答案.
JavaScript的:
$(document).ready(function() { animateDiv(); }); function makeNewPosition($container) { // Get viewport dimensions (remove the dimension of the div) $container = ($container || $(window)) var h = $container.height() - 50; var w = $container.width() - 50; var nh = Math.floor(Math.random() * h); var nw = Math.floor(Math.random() * w); return [nh,nw]; } function animateDiv() { var $target = $('.a'); var newq = makeNewPosition($target.parent()); var oldq = $target.offset(); var speed = calcSpeed([oldq.top,newq); $('.a').animate({ top: newq[0],left: newq[1] },function() { animateDiv(); }); }; function calcSpeed(prev,next) { var x = Math.abs(prev[1] - next[1]); var y = Math.abs(prev[0] - next[0]); var greatest = x > y ? x : y; var speedModifier = 0.1; var speed = Math.ceil(greatest / speedModifier); return speed; }
HTML:
<div id="container"> <div class='a'></div> </div>
CSS:
div#container {height:100px;width:100px;} div.a { width: 50px; height:50px; BACkground-color:red; position:fixed; }
这将允许您创建具有任何高度/宽度的包裹元素,并使浮动元素保持在其容器的区域内.
以上是大佬教程为你收集整理的jquery – 固定容器中的随机运动全部内容,希望文章能够帮你解决jquery – 固定容器中的随机运动所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。