How to pass variable into jquery animate function properties?

后端 未结 1 1239
不思量自难忘°
不思量自难忘° 2021-02-20 10:03
function SlideObject(Side) {
    $(\"#div\").animate({
        margin+Side: \"-1000px\",
        opacity: \"hide\"
    }, 1000);
}

I would like to pass

1条回答
  •  太阳男子
    2021-02-20 10:33

    Firstly, don't use eval() to do this. There's no need and that opens up your site to vulnerabilities if you are in any way using user input as part of that (directly or indirectly). The right way to do this is:

    This is a test

    with CSS:

    #div { padding: 15px; background: yellow; }
    

    and Javascript:

    function slideObject(side) {
      var anim = {opacity: 0};
      anim["margin" + side] = "-1000px";
      $("#div").animate(anim, 1000);
    }
    
    $(function() {
      slideObject("Left");
    });
    

    You'll note that the opacity value is changed to 0. hide is not a valid value for opacity.

    Basically you create the anonymous object and then assign a dynamic property using [].

    0 讨论(0)
提交回复
热议问题