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

Javascript radio buttons mouseover move images with math.random used

本文关键字:使用 math random 图像 移动 单选按钮 鼠标 悬停 Javascript      更新时间:2023-09-26
有点

新编程到一般和弄乱一些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>

检查这是否是你需要的:

$( 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>

你是否在你的项目中包含了jQuery?

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