最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery set css position in animate function - Stack Overflow

programmeradmin1浏览0评论

How would you set the position:relative property in an element that does not have an initial position property set, within jQuery's animate()?

This does not work:

$(mLinks[id]).animate
(
    {
        position:'relative',
        left:'200px'
    }
);

Given that mLinks is a valid DOM element object.

I also tried with the duration and callback parameters.

How would you set the position:relative property in an element that does not have an initial position property set, within jQuery's animate()?

This does not work:

$(mLinks[id]).animate
(
    {
        position:'relative',
        left:'200px'
    }
);

Given that mLinks is a valid DOM element object.

I also tried with the duration and callback parameters.

Share Improve this question asked Dec 12, 2012 at 13:55 LeeLee 3,96912 gold badges49 silver badges66 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

It does not make sense to "animate" the css position attribute isn't it? There is nothing between relative and absolute or static or anything like that...

This is what I would do:

$(mLinks[id]).css('position', 'relative').animate
(
    {
        left:'200px'
    }
);

If you read the corresponding jQuery doc, you will find this:

most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used).

The animate method don't let you to set css attributes and this make sense, although to have a great animation you must set correctly the css attributes, these are two different things.

So first you should set the css attribute. And you should use css method:

$(mLinks[id]).css("position", "relative")

After you can start with the animation:

$(mLinks[id]).animate({ left:'200px' });

Combining all together you'll have:

$(mLinks[id]).css("position", "relative").animate({ left:'200px' });

take a look at this code.

<html>
<head>
    <title>Hello there</title>
    <script type="text/javascript" src = "assets/js/jquery.min.js"></script>
</head>
<body>
    <div class="tobechanged" style = "background:#ddd;position:fixed;">
        hello there.
    </div>
    <script type="text/javascript">
    $('.tobechanged').css('position','relative').animate({
        opacity: 0.9,
        left: '+=50'},
        4000, function() {
        //some stuff here.
    });
    </script>
</body>
</html>

This now should work just fine.

发布评论

评论列表(0)

  1. 暂无评论