How to detect which device view you're on using Twitter Bootstrap API?

后端 未结 7 908
小蘑菇
小蘑菇 2020-12-02 06:54

I have just started to play around with Twitter Bootstrap API for a project I have coming up. The main nav contains 3 main elements:

  • site nav
  • social l
7条回答
  •  被撕碎了的回忆
    2020-12-02 07:24

    If you want to know what environment you're on, try using Bootstrap's own CSS classes. Create an element, add it to the page, apply its helper classes and check if it's hidden to determine if that's the current environment. The following function does just that:

    Bootstrap 4

    function findBootstrapEnvironment() {
        let envs = ['xs', 'sm', 'md', 'lg', 'xl'];
    
        let el = document.createElement('div');
        document.body.appendChild(el);
    
        let curEnv = envs.shift();
    
        for (let env of envs.reverse()) {
            el.classList.add(`d-${env}-none`);
    
            if (window.getComputedStyle(el).display === 'none') {
                curEnv = env;
                break;
            }
        }
    
        document.body.removeChild(el);
        return curEnv;
    }
    

    Bootstrap 3

    function findBootstrapEnvironment() {
        var envs = ['xs', 'sm', 'md', 'lg'];
    
        var $el = $('
    '); $el.appendTo($('body')); for (var i = envs.length - 1; i >= 0; i--) { var env = envs[i]; $el.addClass('hidden-'+env); if ($el.is(':hidden')) { $el.remove(); return env; } } }

    Bootstrap 2

    function findBootstrapEnvironment() {
        var envs = ['phone', 'tablet', 'desktop'];
    
        var $el = $('
    '); $el.appendTo($('body')); for (var i = envs.length - 1; i >= 0; i--) { var env = envs[i]; $el.addClass('hidden-'+env); if ($el.is(':hidden')) { $el.remove(); return env; } } }

提交回复
热议问题