繁体   English   中英

JS通过应用.css使元素移动

[英]JS make element move by applying .css

我想通过应用.css()使元素在箭头按下移动,但它根本不工作,我无法找出原因。 完全相同的代码与JQ animate()完美配合。 你能解释一下为什么.css不工作吗? 我知道有更好的方法可以做到这一点,但我只是好奇为什么它没有附加top属性.Below是带有动画的代码

$(document).ready(function(){
    $('body').keydown(function() {
        if (event.which == 38)
        {
            $('div').animate({top:'-=10px'},'fast');
        }
        else if (event.which == 40)
        {
            $('div').animate({top:'+=10px'},'fast');
        }
        else if (event.which == 37)
        {
            $('div').animate({left:'-=10px'},'fast');
        }
        else if (event.which == 39)
        {
            $('div').animate({left:'+=10px'},'fast');
        }
    }); 
});

移动div需要移动空间,或者你可以使用position:absolute
演示

使用.css()调整属性需要事先显式设置属性,而.animate()将调整元素的计算位置,而不是专门设置它。

在下面的代码片段中,我给出了#movable元素的topleft属性,并在没有它们的情况下留下了另一个<div> 应用.css()的选择器会影响两个<divs> ,但请注意只有具有topleft属性的<div>才会移动。

 $(document).ready(function(){ $('body').keydown(function(event) { if (event.which == 38) { $('div').css({top:'-=10px'}); } else if (event.which == 40) { $('div').css({top:'+=10px'}); } else if (event.which == 37) { $('div').css({left:'-=10px'}); } else if (event.which == 39) { $('div').css({left:'+=10px'}); } //added to stop Stack Overflow scrolling event.preventDefault(); }); }); 
 div { position:relative; } /* Set top and left of the movable div explicitly */ #movable { top:0px; left:0px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="movable">movable</div> <div>immovable</div> 

帖子中的代码是您的真实代码吗? 因为您正在使用event变量,但是您没有为传递给keydown的函数定义任何参数。 它需要是$('body').keydown(function(event) {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM