javascript - jQuery animate problems - dynamically choose direction -
I am using jQuery to move a letter around on a black background. There is no purpose for it, in reality it is just moving around. I have four buttons, left, right, top and bottom, which respectively want to move the letter. But for some reason I have problems with the .animate () method. I know that I can use a switch statement, but I'm going for a more concise solution.
Here is the html:
& lt; Div class = "box" & gt; & Lt; P & gt; This is & lt; / P & gt; & Lt; / Div & gt; & Lt; Div class = "slider-nav" & gt; & Lt; Button data-dir = "left" & gt; Left & lt; / Button & gt; & Lt; Button data-dir = "right" & gt; Right & lt; / Button & gt; & Lt; Button data-dir = "top" & gt; Up & lt; / Button & gt; & Lt; Button data-dir = "bottom" & gt; Down & lt; / Button & gt; & Lt; / Div & gt; And here's JavaScript:
(function ($) {var item = $ ('p'); $ ('button'). ( 'Click', function) (var direction = $ (this) .data ('dir'); move (direction);}); function moves (dir) {var dir = 'margin' + '-' + dir; Object .animate ({dir: '+ = 25px'}, 500);}}}) (jQuery); Thank you for helping to find a problem with my code
You want to use the bracket notation for the dynamic key in your object, which you pass to animate. Besides, I was playing with my idea, and it seems that if you are adjusting the top / left CSS properties (or margin-top / left), then some branching logic to control you right / down Have to do.
JSFIDDLE:
var $ o = $ ('p'); Var option = {"left": 0, "top": 0}; // ... function move (dior, operation) {if (oper === 'add') {options [dir] + = 25; } And {option [dir] - = 25; } $ O.animate (option, 500); };
Comments
Post a Comment