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

后端 未结 7 877
小蘑菇
小蘑菇 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条回答
  •  萌比男神i
    2020-12-02 07:29

    I originally posted answer here, the solution for Bootstrap v.4.x.

    JS breakpoint detection for Twitter Bootstrap 4.1.x

    The Bootstrap v.4.0.0 (and the latest version Bootstrap 4.1.x) introduced the updated grid options, so the old concept on detection may not directly be applied (see the migration instructions):

    • Added a new sm grid tier below 768px for more granular control. We now have xs, sm, md, lg, and xl;
    • xs grid classes have been modified to not require the infix.

    I written the small utility function that respects an updated grid class names and a new grid tier:

    /**
     * Detect the current active responsive breakpoint in Bootstrap
     * @returns {string}
     * @author farside {@link https://stackoverflow.com/users/4354249/farside}
     */
    function getResponsiveBreakpoint() {
        var envs = {xs:"d-none", sm:"d-sm-none", md:"d-md-none", lg:"d-lg-none", xl:"d-xl-none"};
        var env = "";
    
        var $el = $("
    "); $el.appendTo($("body")); for (var i = Object.keys(envs).length - 1; i >= 0; i--) { env = Object.keys(envs)[i]; $el.addClass(envs[env]); if ($el.is(":hidden")) { break; // env detected } } $el.remove(); return env; };

    JS breakpoint detection for Bootstrap v4-beta

    The latest Bootstrap v4-alpha and Bootstrap v4-beta had different approach on grid breakpoints, so here's the legacy way of achieving the same:

    /**
     * Detect and return the current active responsive breakpoint in Bootstrap
     * @returns {string}
     * @author farside {@link https://stackoverflow.com/users/4354249/farside}
     */
    function getResponsiveBreakpoint() {
        var envs = ["xs", "sm", "md", "lg"];
        var env = "";
    
        var $el = $("
    "); $el.appendTo($("body")); for (var i = envs.length - 1; i >= 0; i--) { env = envs[i]; $el.addClass("d-" + env + "-none");; if ($el.is(":hidden")) { break; // env detected } } $el.remove(); return env; }

    I think it would be useful, as it's easy to integrate to any project. It uses native responsive display classes of the Bootstrap itself.

提交回复
热议问题