我有个形象。我希望那个图像能够移动。这很好,但现在我希望这些块也能移动。唯一的问题是,我不能让div
停止对img
的溢出。
我的意思是,当页面加载时,div
块几乎就位于img
的正上方。我想让他们在页面上更远的位置。
我还需要知道如何将空间限制在img
可以移动的位置。如果你能帮我的话,我将不胜感激。
HTML代码
<!DOCTYPE html>
<html>
<head>
<title>Moving Mario</title>
<link rel='stylesheet' type='text/css' href='stylesheet.css'/>
</head>
<body>
<img src="http://i1061.photobucket.com/albums/t480/ericqweinstein/mario.jpg"/>
<div id='div1' class='divs'></div>
<div id='div2' class='divs'></div>
<div id ='div3' class='divs'></div>
<div id ='div4' class='divs'></div>
<script type='text/javascript' src='jquery-2.1.3.min.js'></script>
<script type='text/javascript' src='script.js'></script>
</body>
jQuery码
$(document).ready(function() {
alert("It Worked");
console.log('jquery active')
$(document).keydown(function(key) {
console.log(key);
switch(parseInt(key.which,10)) {
// Left arrow key pressed
case 37:
$('img').animate({left: "-=10px"}, 'fast');
break;
// Up Arrow Pressed
case 38:
$('img').animate({top: "-=10px"}, 'fast');
break;
// Right Arrow Pressed
case 39:
$('img').animate({left: "+=10px"}, 'fast');
break;
// Down Arrow Pressed
case 40:
$('img').animate({top: "+=10px"}, 'fast');
break;
}
});
});
CSS代码
img {
height: 50px;
width: 50px;
position: absolute;
margin:20px;
}
#div1 {
background-color:yellow
}
#div2 {
background-color:green;
}
#div3 {
background-color:blue;
}
#div4 {
background-color:red;
}
html {
background-color: black;
}
.divs {
display:inline-block;
width: 200px;
height: 100px;
margin: 1em;
}
我正在为这个项目使用代码编辑器ATOM。
发布于 2015-04-30 13:39:18
图像之所以高于div,是因为它是绝对的偏序。把它移开。而不是按键处理程序的“左”属性,输入“填充-左”等等。参见示例(单击结果窗格并按右箭头键) http://jsfiddle.net/x3vagg32/
img {
height: 50px;
width: 50px;
/*position: relative;*/
margin:20px;
}
$('img').animate({'padding-left': "+=10px"}, 'fast');
但我真的不明白所期望的结果是什么。
更新
首先,您写到您希望移动块,但现在您希望它们是静态的。如果是这样的话,我认为你应该为所有参与你游戏的元素设定位置。设置适当的左和顶部不仅为形象,也为所有的区块。每次移动图像时,您都应该模拟它的坐标,这样您就可以理解图像是否在其中一个块上移动。
或者在你的游戏中使用一些其他的技巧可能更好。比如画布。
发布于 2015-04-30 13:33:37
首先,在你的图像周围放一个div,以阻止其他div超过它。
https://stackoverflow.com/questions/29968580
复制相似问题