对一般编程和使用一些JS搞乱的新手。我正在努力获得一些理解并帮助解决这个问题。我去过图书馆,试图解决这个问题。
我要做的是有3个单选按钮。我把它们命名为小型,中型,大型,中间有一个div。 div假设位于屏幕中间。此人从单选按钮中选择位移delta。用户将鼠标悬停在彩色div上,然后div将移动到一个随机的新位置(我想的是random()方法),然后是[delta -5,delta +5]之间的位移。
现在。该计划有效。我似乎无法将“div”放在图像的中心,并且在页面上由math.random移动的div很慢?我怎样才能让它更快?
所以这些是我不确定的问题。
1)我如何将div居中?我已经尝试了两次改变位置,但那导致'中心'不是正确的名字,然后尝试顶部和宽度,而不是工作。
2)如何通过math.random使div移动得更快。
3)有没有办法而不是刷新页面,我可以去另一个'收音机',速度会慢下来而不会让这些复杂化?
这是我到目前为止的代码。
<html>
<head></head>
<style>
div.moving{
width: 90px;
height:90px;
background-color:black;
position:absolute;}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1 px <input type="radio" id="s" name="move" value="1" checked="checked"><br>
10 px <input type="radio" id="m" name="move" value="10"><br>
100 px <input type="radio" id="l" name="move" value="100"><br>
<div class='moving' id="mainDiv" onmouseover=" move();"></div>
</body>
<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 + (getRandomIntInclusive(0,stepSize) * [-1,1][Math.floor(Math.random() * 2) * 10] );
var new_top = top + (getRandomIntInclusive(0,stepSize) * [-1,1][Math.floor(Math.random() * 2) * 10] );
$( this ).css('left', new_left + 'px' );
$( this ).css('top', new_top + 'px' );
});});
document.getElementById('mainDiv').style.left="700px";
function getRandomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>
答案 0 :(得分:0)
<html>
<head></head>
<style>
html.body {
width: 100%;
height: 100%;
}
div.moving{
width: 90px;
height:90px;
background-color:black;
position:absolute;
left: 0;
right: 0;
margin: 0 auto;}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1 px <input type="radio" id="s" name="move" value="1" checked="checked"><br>
10 px <input type="radio" id="m" name="move" value="10"><br>
100 px <input type="radio" id="l" name="move" value="100"><br>
<div class='moving' id="mainDiv" onmouseover=" move();"></div>
</body>
<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 + (getRandomIntInclusive(0,stepSize) * [-1,1][Math.floor(Math.random() * 2) * 10] );
var new_top = top + (getRandomIntInclusive(0,stepSize) * [-1,1][Math.floor(Math.random() * 2) * 10] );
$( this ).css('left', new_left + 'px' );
$( this ).css('top', new_top + 'px' );
});});
document.getElementById('mainDiv').style.left="0px";
function getRandomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
</script>