简体   繁体   English

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

[英]JS make element move by applying .css

I wanted to make an element move on arrow press by applying .css() but its not working at all and I cant figure out why. 我想通过应用.css()使元素在箭头按下移动,但它根本不工作,我无法找出原因。 The exactly same code is working perfectly with JQ animate(). 完全相同的代码与JQ animate()完美配合。 Can you explain me why the .css is not working ? 你能解释一下为什么.css不工作吗? I know there are better ways to do this but I'm just curious why its not attaching the top property.Below is the code with animate 我知道有更好的方法可以做到这一点,但我只是好奇为什么它没有附加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');
        }
    }); 
});

Moving div require space to move or you can use position:absolute 移动div需要移动空间,或者你可以使用position:absolute
Demo 演示

Using .css() to adjust a property requires that property to be explicitly set beforehand, whereas .animate() will adjust the calculated position of an element without it being specifically set. 使用.css()调整属性需要事先显式设置属性,而.animate()将调整元素的计算位置,而不是专门设置它。

In the below snippet, I have given the #movable element top and left properties, and left the other <div> without them. 在下面的代码片段中,我给出了#movable元素的topleft属性,并在没有它们的情况下留下了另一个<div> The selector that .css() is applied to affects both <divs> , but note that only the <div> with the top and left properties moves. 应用.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> 

Is the code in the post your real code? 帖子中的代码是您的真实代码吗? Because you're using an event variable, but you haven't defined any argument to the function passed to keydown . 因为您正在使用event变量,但是您没有为传递给keydown的函数定义任何参数。 It needs to be $('body').keydown(function(event) { . 它需要是$('body').keydown(function(event) {

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

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