键盘控制div移动

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>键盘控制div移动</title>
<style>
div{width:100px;height:100px;background:red;position:absolute;}
</style>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).keydown(function(ev){
var l=$("div").offset().left;
var t=$("div").offset().top;
if(ev.which==39){
$("div").css("left",(l+10));
}
if(ev.which==37){
$("div").css("left",(l-10));
}
if(ev.which==38){
$("div").css("top",(t-10));
}
if(ev.which==40){
$("div").css("top",(t+10));
}
});
</script>
</head>
<body>
<div></div>
</body>
</html>

补充:

alert($('div').width()); //不包含 padding border与大小有关
alert($('div').innerWidth()); //包含内边距 padding
alert($('div').outerWidth()); //包含内边距 padding+边框 border
alert($('div').outerWidth(true)); //包含内边距 padding+边框 border+外边距 margin

posted @ 2016-10-26 21:06  2350305682  阅读(619)  评论(0编辑  收藏  举报