简体   繁体   中英

Twitter Bootstrap Popover: how to set “placement” depending on screen size?

I'm trying to use http://twitter.github.io/bootstrap/javascript.html#popovers . On larger screens, I want the popover to appear on the right. On smaller screens, I think I want it to appear either at the top or bottom. Is there a way to do this?

I put responsive placement attributes on my elements, such as data-placement-xs="top" data-placement-md="left" and use the following piece of JavaScript to initialize my tooltips in all of the pages:

$('[data-toggle="tooltip"]').tooltip({
    'placement': function(tt, trigger) {
        var $trigger = $(trigger);
        var windowWidth = $(window).width();

        var xs = $trigger.attr('data-placement-xs');
        var sm = $trigger.attr('data-placement-sm');
        var md = $trigger.attr('data-placement-md');
        var lg = $trigger.attr('data-placement-lg');
        var general = $trigger.attr('data-placement');

        return (windowWidth >= 1200 ? lg : undefined) ||
            (windowWidth >= 992 ? md : undefined) ||
            (windowWidth >= 768 ? sm : undefined) ||
            xs ||
            general ||
            "top";
    }
});

Most people use CSS media queries for responsive designs, we can do the exact same thing in javascript.

//detect devicen width
if(screen.width < somevalue){

}else if(screen.width > somevalue){

}

Would be the same as the media query equivalent of device-width

Or, if you preferred to use the visible width

//detect visible width
if(document.documentElement.clientWidth < somevalue){

}else if(document.documentElement.clientWidth > somevalue){

}

This will be consistent across all browsers and devices with media-queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM