我有一张图片。我希望那个图像能够移动。效果很好,但现在我希望这些 block 也能移动。唯一的问题是我无法让 div
停止溢出 img
。
我的意思是当页面加载时,div
block 几乎位于 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。
最佳答案
图像位于 div 之上,因为它是绝对后置的。去掉它。而不是 keydown 处理程序的 'left' 属性键入 'padding-left' 等等。查看示例(单击结果 Pane 并按右箭头键)http://jsfiddle.net/x3vagg32/
img {
height: 50px;
width: 50px;
/*position: relative;*/
margin:20px;
}
$('img').animate({'padding-left': "+=10px"}, 'fast');
但我实在想不明白想要的结果是什么。
更新
一开始您写的是要移动 block ,但现在您希望它们是静态的。如果是这样,我认为您应该为所有参与游戏的元素设置 position:ablsolute。不仅为图像而且为所有 block 设置适当的左侧和顶部。每次移动图像时,您都应该检查它的坐标,这样您就可以了解图像是否移动到其中一个 block 上。
或者为您的游戏使用一些其他技术可能会更好。例如, Canvas 。
关于javascript - 定位和限制麻烦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29968580/