jQuery: Slide animation goes to far, then “jumps”

2019-08-31 04:37发布

I've seen a few questions about a similar issue, but I haven't found a solution that makes sense to me yet. The problem is on the JSFiddle here: http://jsfiddle.net/twchapman/EEXjR/2/

Click on Portfolio to see the behavior.

The functions I wrote:

function changeTab(tab) {
    active = tab;
    $("#" + tab).slideDown(animspeed);
}

function change(tab) {
    if (tab == active) return;
    $("#" + active).slideUp(animspeed, function () {
        changeTab(tab);
    });
}

I'm only using Chrome, but I'm pretty sure you'll get this error on any browser: when the page loads, it slides the content div down, and clicking the links (only Portfolio actually works at the moment) will slide the current div up, then the correct one down.

It's working almost completely as intended, but with one minor issue: when the animations begin, the div's height "jumps", and it's momentarily taller while the animation takes place, then "jumps" to the correct size when finished.

The two common solutions I've found have suggested: 1. Add a width to the style of the div, which already exists, and 2. change the height/margin parameters of the slide function when it's called. To me, the second solution seems like it shouldn't be necessary, as I don't provide any options other than an animation length.

I'm hoping this is just me missing something and being silly, not a big problem with the way I'm doing things.

2条回答
我命由我不由天
2楼-- · 2019-08-31 04:47

Update your js.

function change(tab) {
    if(tab == active) return false;
    console.log(tab);
    console.log(active);
    if($("#" + active).length){   //check element is exists.
       $("#" + active).slideUp(animspeed, function() {changeTab(tab)})
    }else{
    changeTab(tab);
    }

}
查看更多
ら.Afraid
3楼-- · 2019-08-31 04:55

The problem comes from padding which at times can make jQuery animations jittery. A fast solution for your problem is to leave your Js untouched and use a natural box model for your layout.

In your css just include:

* { -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box; 
            box-sizing: border-box; }

I really suggest to read this Paul Irish blog post and to include this code in all your projects.

Here's a working demo: http://jsfiddle.net/gleezer/EEXjR/3/

查看更多
登录 后发表回答