jQuery addClass method chaining to perform CSS transitions

前端 未结 4 550
独厮守ぢ
独厮守ぢ 2021-01-16 09:06

What I would like to do (broke):

相关标签:
4条回答
  • 2021-01-16 09:19

    Your transition works in case three when it calls $('div').css('left') because jQuery will call the method window.getComputedStyle (or a very similar method depending on browser compatibility issues). In a blog post by Tim Taubert (a Mozilla Employee), the trick is described:

    getComputedStyle() in combination with accessing a property value actually flushes all pending style changes and forces the layout engine to compute our <div>’s current state.

    Without forcing this layout recalculation, the recalculation is delayed until after both classes (left and left-more) are added, which will calculate its position at 400px.

    Example Fiddle - using getComputedStyle and accessing .left

    0 讨论(0)
  • 2021-01-16 09:32

    Good question! This behaviour definitely seems weird at first. It's also a little tricky to explain this clearly, but to start, understand the following:

    1) Javascript functions execute atomically

    In JS, functions always run from beginning to end without any possibility of some other operation occurring midway through. This is the same as saying that JS is a single-threaded language.

    2) The browser can't interrupt javascript either

    Not only is JS code prevented from running midway through a function, but the browser tab in which the code is running will also not interject! This means that (nearly) EVERYTHING on a webpage is halted (repaints, animations, stylesheet application, etc) when a JS function is running. If you want to test this, you can try running while (true) { var i = 'yo'; } in the console. (Warning: this will make you sad)

    3) State inside of JS functions is invisible to browsers

    Because the browser can't interrupt in the middle of a JS function it means the browser can never know any state that occurs mid-way through said function. The browser can only act based off of the state that remains once a function finishes. Not clear? To illustrate:

    var someGlobalValue = null;
    
    function lol() {
        someGlobalValue = 'hi';
        someGlobalValue = 'hello';
        someGlobalValue = 'ok';
    }
    

    When the function lol is run, someGlobalValue assumes multiple values, but the browser will only ever be aware of the last one, because it would have to interject midway through in order to see the others (which it can't do!)

    4) CSS State inside of JS functions is similarly invisible to browsers

    The same applies to css state! (And now you may see that I am, in fact, beginning to answer your question).

    If you call the following function:

    function lol() {
        $('.thing').css('left', '10px');
        $('.thing').css('left', '30px');
    }
    

    The browser will never apply the left: 10px value because it takes no actions midway through a function! Only the results of a function, one it is complete, can be worked with by the browser.

    Answering your questions!!

    fiddle 1

    The left_more class is added immediately after the left class - the browser never sees the left class, and applies css styling after the function ends - applying the left_more class, but since no initial left value was present there is no animation. (The css cascades; while both classes are present, left_more fully overwrites left)

    fiddle 2

    Same issue - the left class is overwritten before the browser can process it

    fiddle 3

    This works because the value is set with a call to css, and then is NOT overwritten because addClass is used to set where the value should animate to. The console.log is irrelevant - all that is important is the css function call. Once that function completes, there are 2 pieces of information, 1 being the css value, the other being the class value. This contrasts the other example where there is only one piece of information left after the function runs: the class value.

    If you wanted to work with only classes, and still get the transition going, the flow would have to look like this:

    1) Add left class 2) Exit function, which allows the browser to view the state 3) Add left_more class

    Sry for the essay lol. But I think this needed a long explanation because of the subtlety of the issue.

    0 讨论(0)
  • 2021-01-16 09:35

    "CSS3 transitions allows you to change property values smoothly (from one value to another), over a given duration."

    1st Scenario posted :

    In order to have the css transition to work, you need to specify the css property to the element on which you want to do the transition. In your example, you are doing a transition on the left property but it's initial value is not defined in the div css.

    In order to fix it, just add left property.

    div {
        position: absolute;
        width: 10px;
        height: 10px;
        background-color: red;
        left: 0px;
    }
    

    Working example : http://jsfiddle.net/0bm4wq7h/14/

    2nd scenario posted vs 3rd scenario posted:

    Even though both examples doesn't have left property defined for the div, the reason why the 3rd scenario works as compared to the 2nd scenario is because of the delay caused by console.log.

    In the first statement,

    $('div').css({
            'transition': 'left 1000ms'
        }).addClass('left');
    

    class left is added to the div element, which internally adds the left property. But adding the console.log($('div').css('left') invokes window.getComputedStyle ( as mentioned by Stryner ) which registers the computed value and adding $('div').addClass('left_more'); basically gives it an opportunity to perform the transition from left : 100px to left : 600px.

    0 讨论(0)
  • 2021-01-16 09:42

    There are several issues going on here. In the examples given, the reason that the transition does not occur when the first left class is added is because in order for the rendering engine to animate a property, that property needs to have a value already. In this case, there is no value for left and as a result the transition does not occur.

    The reason why it does not work when chained is because of specificity. jQuery will add both classes and when the call to render the page is made the last added definition for left is applied due to their shared specificity.

    The reason why it appears to work from adding the class at a separate time versus chained is because the rendering engine was implicitly called from jQuery when the console.log accessed the css values of the element. This was pointed out by Stryner in his answer here: https://stackoverflow.com/a/33902053/1026459 . It was a very nice find.

    Here is an example of that being applied so that the value of left doesn't need to be guessed at.

    The meat of what happens is the offset of the element is found to get the pixel offset for left. Then that value is applied to the left style property. At that point while the element still hasn't changed position the rendering engine is called to update the left property. The property is then removed to ensure that the specificity does not take precedence over the class definition, and then the class definition is applied. This will facilitate the transition on first encounter.

    jsFiddle Demo

    $('button').click(function() {
        $('div').css({'transition':'left 1000ms'}).each(function(){	
            $(this).css('left',$(this).offset().left); 
            window.getComputedStyle(this,null).getPropertyValue("left");
        }).css('left','').addClass('left');
    });
    button {
        margin-top: 30px;
    }
    
    div {
        position: absolute;
        width: 10px;
        height: 10px;
        background-color: red;
    }
    
    .left {
        left: 100px;
    }
    
    .left_more {
        left: 400px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div></div>
    <button>go</button>

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