开发者

passing style as argument to jquery animate

开发者 https://www.devze.com 2023-01-28 10:12 出处:网络
so i have a function for handling elements with a hover, however i want to be able to pass in the css styles as an argument.i have tried different variations, but this is currently my code (just the n

so i have a function for handling elements with a hover, however i want to be able to pass in the css styles as an argument. i have tried different variations, but this is currently my code (just the necessary portion)...

function load_hovers(mouseOverCss){
  $('.hover').hover(function(){
    $(this).animate({
      eval(mouseOverCss)
    }, 500, function() {
    });

and i call load_hovers("backgroundColor: 'red'");

this returns an error invalid object initializer $(this).animate({. without using eval, 开发者_开发知识库the error is missing : after property id {eval(mouseOverCss)}\n.

any suggestions?


You're probably better to stay away from the Eval option (Eval is evil and all that...) and try passing in an object to your method instead.

First create an object for your CSS argument:

var css = {};
css.Property = 'backgroundColor';
css.Value = 'Red';

Then you can pass this (or an array of them, if you need multiple properties) to your method:

function load_hovers(classes)
{
    $('.hover').hover(function(){
      $(this).animate({
        $(this).css(classes.Property, classes.Value); // or iterate over an array of these
      }, 500, function() {
      });
    });
}


got it.

var mouseOverCss = {};
mouseOverCss['backgroundColor'] = 'red';
mouseOverCss['paddingLeft'] = '100px';
load_hovers(mouseOverCss);

and then just

$(this).animate(mouseOverCss, duration);

thanks Phil for getting me on the path of not just sending a string pre-formatted for animate()!

0

精彩评论

暂无评论...
验证码 换一张
取 消