28

私はこれに対する答えを見つけるためにグーグルをやっていますが、運がありませんでした。私は少しアマチュアで、検索する適切な用語がわからないためかもしれませんが、ここの誰かが私を正しい方向に導いたり、助けてくれたりするかもしれません。

とにかく、私はdivをランダムに、スムーズにページ内を移動させる方法を探しています。背景色が表示されます。この画像は、一見ランダムに、無限にページ内を移動したいと思います。「DVD」が浮かんでいるDVDプレーヤーのホーム画面の背景によく似ています。

divの開始点は重要ではなく、終了点も重要ではありません。ユーザーがそのページを表示している間、ページ内をランダムに移動する必要があります。

私はまともなHTMLとCSSのスキル、非常に基本的なJSのスキル、そしてjQueryの実装の経験を持っています。理想的には、自分で実装できるものが欲しいです。

前もって感謝します!!!

4

7 に答える 7

47

基本的な前提は、位置の値を生成し、jqueryのanimate()関数を使用してdivを移動することです。次の位置の計算は簡単です、あなたはほんの少しの数学が必要です。これが私がノックアップした非常に基本的なjsfiddleです。それはおそらく遅延タイマー、それがどれだけ動きすぎたかに基づいて動的に計算する速度で行うことができますが、それはあなたに私が望む出発点を与えます。

http://jsfiddle.net/Xw29r/

速度修飾子を使用してサンプルコードを更新しました:

http://jsfiddle.net/Xw29r/15/


何らかの理由でこれはまだ注目を集めているので、CSSトランジションを使用する更新された回答があります。これははるかにスムーズなはずです。

http://jsfiddle.net/bf9nv1q6/

function RandomObjectMover(obj, container) {
	this.$object = obj;
  this.$container = container;
  this.container_is_window = container === window;
  this.pixels_per_second = 250;
  this.current_position = { x: 0, y: 0 };
  this.is_running = false;
}

// Set the speed of movement in Pixels per Second.
RandomObjectMover.prototype.setSpeed = function(pxPerSec) {
	this.pixels_per_second = pxPerSec;
}

RandomObjectMover.prototype._getContainerDimensions = function() {
   if (this.$container === window) {
       return { 'height' : this.$container.innerHeight, 'width' : this.$container.innerWidth };
   } else {
   	   return { 'height' : this.$container.clientHeight, 'width' : this.$container.clientWidth };
   }
}

RandomObjectMover.prototype._generateNewPosition = function() {

	// Get container dimensions minus div size
  var containerSize = this._getContainerDimensions();
	var availableHeight = containerSize.height - this.$object.clientHeight;
  var availableWidth = containerSize.width - this.$object.clientHeight;
    
  // Pick a random place in the space
  var y = Math.floor(Math.random() * availableHeight);
  var x = Math.floor(Math.random() * availableWidth);
    
  return { x: x, y: y };    
}

RandomObjectMover.prototype._calcDelta = function(a, b) {
	var dx   = a.x - b.x;         
  var dy   = a.y - b.y;         
  var dist = Math.sqrt( dx*dx + dy*dy ); 
  return dist;
}

RandomObjectMover.prototype._moveOnce = function() {
		// Pick a new spot on the page
    var next = this._generateNewPosition();
    
    // How far do we have to move?
    var delta = this._calcDelta(this.current_position, next);
    
		// Speed of this transition, rounded to 2DP
		var speed = Math.round((delta / this.pixels_per_second) * 100) / 100;
    
    //console.log(this.current_position, next, delta, speed);
          
    this.$object.style.transition='transform '+speed+'s linear';
    this.$object.style.transform='translate3d('+next.x+'px, '+next.y+'px, 0)';
    
    // Save this new position ready for the next call.
    this.current_position = next;
  
};

RandomObjectMover.prototype.start = function() {

	if (this.is_running) {
  	return;
  }

	// Make sure our object has the right css set
  this.$object.willChange = 'transform';
  this.$object.pointerEvents = 'auto';
	
  this.boundEvent = this._moveOnce.bind(this)
  
  // Bind callback to keep things moving
  this.$object.addEventListener('transitionend', this.boundEvent);
  
  // Start it moving
  this._moveOnce();
  
  this.is_running = true;
}

RandomObjectMover.prototype.stop = function() {

	if (!this.is_running) {
  	return;
  }
  
  this.$object.removeEventListener('transitionend', this.boundEvent);
  
	this.is_running = false;
}


// Init it
var x = new RandomObjectMover(document.getElementById('a'), window);


// Toolbar stuff
document.getElementById('start').addEventListener('click', function(){
	x.start();
});
document.getElementById('stop').addEventListener('click', function(){
	x.stop();
});
document.getElementById('speed').addEventListener('keyup', function(){
  if (parseInt(this.value) > 3000 ) {
 		alert('Don\'t be stupid, stupid');
    this.value = 250;
  }
	x.setSpeed(parseInt(this.value));
});


// Start it off

x.start();
div#toolbar {
  position:fixed;
  background:#20262F;
  width:100%;
  text-align:center;
  padding: 10px
}
div#a {
width: 50px;
height:50px;
background-color:red;
position:absolute;
}
<div id="toolbar">
<button id="start">Start</button>
<button id="stop">Stop</button>
<input type="number" value="250" id="speed" />
</div>
<div id='a'></div>

于 2012-04-30T15:23:47.203 に答える
8

これを試して:

function moveDiv() {
    var $span = $("#random");

    $span.fadeOut(1000, function() {
        var maxLeft = $(window).width() - $span.width();
        var maxTop = $(window).height() - $span.height();
        var leftPos = Math.floor(Math.random() * (maxLeft + 1))
        var topPos = Math.floor(Math.random() * (maxTop + 1))

        $span.css({ left: leftPos, top: topPos }).fadeIn(1000);
    });
};

moveDiv();
setInterval(moveDiv, 5000);

フィドルの例

于 2012-04-30T15:23:09.380 に答える
6

さて、あなたはの寸法をキャプチャする必要がありますwindow

generate random numbers <=次に、heightwidthscreen(マイナスwidth/heightbox)が必要になります

ボックスにabsolute位置を与え、ボックスに生成されたものを与えるxy coordinates

次に、タイマーを設定してthis function再度呼び出します。

:)

$(document).ready(function() {
    randoBox = {
      width:$("body").width(),
      height:$("body").height(),
      x:0,
      y:0,
      el:null,
      time:1000,
      state:"active",
      init: function(){
        el = $(document.createElement('div'));
        el.attr("style","position:absolute;left:"+this.x+";top:"+this.y+";");
        el.html("DVD")            
        el.height(100);
        el.width(100);
        $("body").append(el);
      },
      move:function(){
        this.y = Math.random()*this.height+1;
        this.x = Math.random()*this.width+1;
        el.attr("style","position:absolute;left:"+this.x+";top:"+this.y+";");            
      },
      run:function(state){
        if (this.state == "active" || state){
          this.move();
          setTimeout(function(){this.run()},this.time);
        }
      }
    }
    randoBox.init();
    randoBox.run(true);
});
于 2012-04-30T15:13:45.037 に答える
2

編集DVDアイドル画面のようにランダムな動きを追加しましたが、どこでも跳ね返ることができます。

http://jsfiddle.net/ryXBM/2/

dirR = "+=2";
dirL = "+=2";

function moveDir() {
 if (Math.random() > 0.95) {
  swapDirL();
 }
 if (Math.random() < 0.05) {
  swapDirR();
 }
}

function swapDirL() {
    dirL == "+=2" ? dirL = "-=2" : dirL = "+=2"; 
}

function swapDirR() {
    dirR == "+=2" ? dirR = "-=2" : dirR = "+=2";   
}

setInterval (function() { $("#d").css("left", dirL); $("#d").css("top", dirR); moveDir(); } , 50)​

CSS

#d { position: absolute;
 left: 100px;
 top: 100px;
 width: 100px;
 height: 100px;
 background-color: #fce;   
}​
于 2012-04-30T15:16:43.550 に答える
1

jQuery SlideMath.random()を使用して、移動する距離として使用する1つの乱数と、移動する方向を決定するための別の乱数を生成できます。

于 2012-04-30T15:13:04.963 に答える
0

topアニメーションの境界線を指定する必要があります。属性と属性の最大値はleftいくつですか。その後、必要なのは、.animate()何度も呼び出される関数だけです。

このようなものが機能するはずです-

var maxLeft = _left_border - $('#selectedElement').width(); // counter intuitively this is actually the right border
var maxTop = _top_border  - $('#selectedElement').height();
var animationDurration = _duration;

function randomAnimation(){
  var randomLeft = Math.floor(Math.random()*maxLeft);
  var randomTop = Math.floor(Math.random()*maxTop);

  $('#selectedElement').animate({
     left: randomLeft,
     top: randomTop
   }, animationDurration, function() {
     randomAnimation();
   });
}
于 2012-04-30T15:14:34.050 に答える
0
<html>
    <head>
        <link rel="stylesheet" href="sample1.css">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                    $('.btn').mouseover(function(){
                        $(this).css({
                            left:(Math.random()*$(window).width()-20),
                            top:(Math.random()*$(window).height()-20),      
                        });
                    });              
            });
        </script>
    </head> 
    <body>
        <div class="btn" style="position: absolute">button</div>
    </body>
</html> 
于 2013-10-24T11:47:49.687 に答える