Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery动画问题-动态选择方向_Javascript_Jquery_Jquery Animate - Fatal编程技术网

Javascript jQuery动画问题-动态选择方向

Javascript jQuery动画问题-动态选择方向,javascript,jquery,jquery-animate,Javascript,Jquery,Jquery Animate,我使用jQuery在黑色背景上移动字母。没有目的,真的只是胡闹。我有四个按钮,左、右、上、下,分别用来移动字母。但是由于某种原因,.animate()方法出现了问题。我知道我可以使用switch语句,但我要寻找一个更简洁的解决方案 以下是html: <div class="box"> <p>O</p> </div> <div class="slider-nav"> <button data-dir="left"&

我使用jQuery在黑色背景上移动字母。没有目的,真的只是胡闹。我有四个按钮,左、右、上、下,分别用来移动字母。但是由于某种原因,.animate()方法出现了问题。我知道我可以使用switch语句,但我要寻找一个更简洁的解决方案

以下是html:

<div class="box">
    <p>O</p>
</div>

<div class="slider-nav">
    <button data-dir="left">Left</button>
    <button data-dir="right">Right</button>
    <button data-dir="top">Up</button>
    <button data-dir="bottom">Down</button>
</div>

如果您能帮我找到代码中的问题,我将不胜感激。谢谢

对于传递给动画的对象文字中的动态关键点,需要使用括号表示法。另外,我一直在玩弄你的想法,如果你正在调整上/左css属性(或页边距上/左),看起来你仍然需要做一些分支逻辑来处理右/下

JSFIDDLE:


不能将字符串用作对象中的键。您可以通过eval函数来实现,但我不推荐这样做。我想这样说:

function move(dir) {
    var distance = 25,
        dir = 'margin' + '-' + dir,
        animation = {},
        previousValue = parseInt($element.css(dir), 10);

    animation[dir] = previousValue + 25;
    $element.animate(animation, 500);
};
下面是一个工作示例:

此外,这将仅设置边距动画,如果您希望在单击按钮时将元素设置为方向动画,则需要执行左、右位置或边距的递增/递减操作。例如:


希望这会有所帮助:)

第一页边距属性应为驼峰式->边距左侧、边距右侧。。。第二个更大的问题是:若您在控制台中检查生成的HTML,您将看到获取dir属性…所以,您不能将已生成的字符串作为animate()函数的参数。也许这会有帮助:
var $o = $('p');
var options = {
    "left":0,
    "top":0
};

//...

function move(dir,oper) {
    if (oper === 'add') {
      options[dir] += 25;
    }
    else {
      options[dir] -= 25;
    }

  $o.animate(options,500);
};
function move(dir) {
    var distance = 25,
        dir = 'margin' + '-' + dir,
        animation = {},
        previousValue = parseInt($element.css(dir), 10);

    animation[dir] = previousValue + 25;
    $element.animate(animation, 500);
};