$(document).ready(function(){
//法1
$(document).on('keydown','div',function(){
$(this).animate(
{left: "+=10px"},
500);
});
//法2
$(document).keydown(function(){
$('div').animate(
{left: "+=10px"},
500);
});
});
问题1:我想法1,法2,功能一样,但是为什么法1的写法不正确?
$(document).ready(function() {
$(document).keydown(function(key) {
switch(parseInt(key.which,10)) {
// Left arrow key pressed
case 37:
$('img').animate({left: "-=10px"}, 'fast');
break;
// Up Arrow Pressed
case 38:
// Put our code here
$('img').animate({top: "-=10px"}, 'fast');
break;
// Right Arrow Pressed
case 39:
// Put our code here
$('img').animate({left: "+=10px"}, 'fast');//代码2
break;
// Down Arrow Pressed
case 40:
// Put our code here
$('img').animate({top: "+=10px"}, 'fast');
break;
}
});
});
问题2:我想把代码2那一行改成$('img').animate({right: "-=10px"}, 'fast');
为何不行,没有效果?
问题一:
如果把事件改为“click”,测试就没问题
keydown
问题二:默认情况下,浏览器进行页面布局基本过程是以浏览器可见区域为画布,左上角为(0,0)基础坐标,从左到右,从上到下从DOM的根节点开始画。所以img相对自身定位也是默认以左上角作参考系的,动画设置left/top参数起作用。如果把浏览器默认的渲染方式改为
html{direction: rtl;}
,这时设置right/top参数起作用。Web底层剖析,浏览器是如何工作的
先前我只测试了向右移没有问题,没有做整体测试(左移之后再右移),表述有误,抱歉