CSS3 transitions inside jQuery .css()

后端 未结 2 514
既然无缘
既然无缘 2020-12-08 01:07

When I add the transition line into my code it breaks jQuery. How can I fix it?

a(this).next().css({
    left: c,
    transition: \'opacity 1s ease-in-out\'
         


        
2条回答
  •  佛祖请我去吃肉
    2020-12-08 02:03

    Step 1) Remove the semi-colon, it's an object you're creating...

    a(this).next().css({
        left       : c,
        transition : 'opacity 1s ease-in-out';
    });
    

    to

    a(this).next().css({
        left       : c,
        transition : 'opacity 1s ease-in-out'
    });
    

    Step 2) Vendor-prefixes... no browsers use transition since it's the standard and this is an experimental feature even in the latest browsers:

    a(this).next().css({
        left             : c,
        WebkitTransition : 'opacity 1s ease-in-out',
        MozTransition    : 'opacity 1s ease-in-out',
        MsTransition     : 'opacity 1s ease-in-out',
        OTransition      : 'opacity 1s ease-in-out',
        transition       : 'opacity 1s ease-in-out'
    });
    

    Here is a demo: http://jsfiddle.net/83FsJ/

    Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:

    $('a').on('click', function () {
        var myTransition = ($.browser.webkit)  ? '-webkit-transition' :
                           ($.browser.mozilla) ? '-moz-transition' : 
                           ($.browser.msie)    ? '-ms-transition' :
                           ($.browser.opera)   ? '-o-transition' : 'transition',
            myCSSObj     = { opacity : 1 };
    
        myCSSObj[myTransition] = 'opacity 1s ease-in-out';
        $(this).next().css(myCSSObj);
    });​
    

    Here is a demo: http://jsfiddle.net/83FsJ/1/

    Also note that if you specify in your transition declaration that the property to animate is opacity, setting a left property won't be animated.

提交回复
热议问题