Javascript单选按钮鼠标悬停使用math.random移动图像

时间:2016-02-11 02:26:04

标签: javascript jquery html css

对一般编程和使用一些JS搞乱的新手。我正在努力获得一些理解并帮助解决这个问题。我去过图书馆,试图解决这个问题。

我要做的是有3个单选按钮。我把它们命名为小型,中型,大型,中间有一个div。 div假设位于屏幕中间。此人从单选按钮中选择位移delta。用户将鼠标悬停在彩色div上,然后div将移动到一个随机的新位置(我想的是random()方法),然后是[delta -5,delta +5]之间的位移。

我该如何解决这个问题?你能帮我吗?感谢。

这是我到目前为止的代码。

 <html>
<head></head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2>Choose step size:</h2>
1 px <input type="radio" id="small" name="move" value="1" checked="checked"><br>
10 px <input type="radio" id="medium" name="move" value="10"><br>
100 px <input type="radio" id="large" name="move" value="100"><br>

<div class='a' id="mainDiv" onmouseover=" move();"></div>

<script type="text/javascript">
$( document ).ready( function(){  
  $('#mainDiv').mouseover(function(){
      var stepSize = parseInt( $('input[type=radio][name=move]:checked').val() );

      var pos = $( this ).position();
      var left = parseInt( pos.left );
      var top = parseInt( pos.top );

      var new_left = left + stepSize;
      var new_top = top + stepSize;    

      $( this ).css('left', new_left + 'px' );
      $( this ).css('top', new_top + 'px' );
  });});
</script>
<style>
div.a {
  width: 80px;
  height:80px;
  background-color:blue;
  position:absolute;

}
</style>

2 个答案:

答案 0 :(得分:0)

检查这是否是您所需要的:

$( document ).ready( function(){  
  $('#mainDiv').mouseover(function(){
      var stepSize = parseInt( $('input[type=radio][name=move]:checked').val() );

      var pos = $( this ).position();
      var left = parseInt( pos.left );
      var top = parseInt( pos.top );
      
      var new_left = left + (getRandomIntInclusive(0,stepSize) * [-1,1][Math.floor(Math.random() * 2)] );
      var new_top = top + (getRandomIntInclusive(0,stepSize) * [-1,1][Math.floor(Math.random() * 2)] );    

      $( this ).css('left', new_left + 'px' );
      $( this ).css('top', new_top + 'px' );
  });});

function getRandomIntInclusive(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
div.a {
  width: 80px;
  height:80px;
  background-color:blue;
  position:absolute;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2>Choose step size:</h2>
1 px <input type="radio" id="small" name="move" value="1" checked="checked"><br>
10 px <input type="radio" id="medium" name="move" value="10"><br>
100 px <input type="radio" id="large" name="move" value="100"><br>

<div class='a' id="mainDiv" onmouseover=" move();"></div>

答案 1 :(得分:0)

您是否在项目中包含了jQuery?

<script src="jquery-2.1.1.min.js"></script>