Setting flexbox display with jquery for multiple browsers?

having a bit of trouble. I need to have something switch from display: none to display: flex, display: flex-box, and display: -ms-flexbox but it seems to be breaking my code.. Here's what I have so far:

$(elem).css({'display': 'flex', 'display': '-webkit-flex', 'display':'-ms-flexbox'});

and while this works:

$(elem).css({'display': 'flex'})

I need to have the other two for safari and IE10. Is there any way of writing this so that it doesn't break my code? Jquery seems confused by this syntax.


I just ran across the same issue. The problem is that you can't specify multiple values of display in the same object, because you can only have one object member called display .

If you're not worried about accidentally removing any other element-level styles, this is one way around:

$(elem).attr('style', 'display: -webkit-flex; display: flex');

(and of course add the extra one for IE10 if you need to).

Sorry to be so late to the party, but maybe it will help others.


I too ran into this issue and @eaj has excellent insight into why this occurs. I took a slightly different approach since I was using flexbox on other elements. I assigned a class like this:

.flex-container{
    display: -webkit-box !important;
    display: -moz-box !important;
    display: -ms-flexbox !important;
    display: -webkit-flex !important;
    display: flex !important;
}

Then instead of trying to change it via adding inline styles, you can just add the class like so:

$(elem).addClass('flex-container');

The !important in the class will override the existing display:none forcing it into visibility. There are a couple of advantages here: it's a lot cleaner semantically, it's easier to add additional flexbox properties if you need them (my actual .flex-container class had ~20 different properties due to the prefixes for center alignment), easier to reuse the same class for other elements, and finally if you need the element to dissappear again gracefully you can just call removeClass().


Since jQuery 1.8.0 no need to add vendor prefix. Cordialy Frederic

链接地址: http://www.djcxy.com/p/75608.html

上一篇: flex之间有什么区别

下一篇: 使用jQuery为多个浏览器设置flexbox显示?