Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

html - Javascript animate CSS float property

I have a class added via JavaScript which makes a section float right and for this section class I want to animate the floating into it's position, however I have not found anyway to make this work. Is there a way to use css3 to animate floating?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It isn't possible using CSS alone for the reason's stated above. But check out Darcy Clark's answer on this post:

http://www.quora.com/Is-there-a-way-in-jquery-to-animate-an-element-from-a-float-right-position-to-a-float-left-position

He links to this fiddle and seems to have figured it out:

http://jsfiddle.net/darcyclarke/m9pTN/

HTML

<div class="float right"></div>
<div class="float left"></div>

CSS

.float {
    background: red;
    width: 50px;
    height: 50px;
    margin: 0 10px;
    display: block;
    float: left; 
    clear: both;
}

.left {
    background: blue;
    float: right;  
}

JS

(function(){
    var $plugin = jQuery.sub();
    $plugin.fn.animate = function(props, speed, cb){
        if(typeof(speed) == "function")
            cb = speed, speed = 500;
        if(typeof(cb) != "function")
            cb = function(){};
        return $.each(this, function(i, el){
            el = $(el);
            if(props.float && props.float != el.css("float")){
                var elem = el.clone().css(props).insertBefore(el),
                    temp = (props.float == el.css("float")) ? elem.position().left : el.position().left;
                props.marginLeft = elem.position().left;
                elem.remove();
                el.css({float:"left",marginLeft:temp});
            }
            $(this).animate(props, speed, function(){
                $(this).css(props);
                cb();
            });
        });
    };

    $(".float.right").bind("click", function(){
        $plugin(this).animate({float:"right"}, 1000); 
    });

    $(".float.left").bind("click", function(){
        $plugin(this).animate({float:"left"}, 1000); 
    });

})();

I can't speak to whether or not doing this is actually a good idea.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...