gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:25:22 25 4
gpt4 key购买 nike

对于一般编程和使用一些 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>

关于使用 math.random 的 Javascript 单选按钮鼠标悬停移动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35329745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com