how to make colorbox responsive

前端 未结 16 1089
情歌与酒
情歌与酒 2021-01-30 13:35

I am using colorbox in a responsive website.

I have a request : I wish that Colorbox automatically adjusts itself to the size and orientation of the screen / mobile devi

16条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 13:44

    I would like to add an answer here. I had a requirement to make the colorbox responsive by respecting different breakpoint widths and change the width of the popover based on window width. Basically, I can afford to have empty spaces to the left and right of the colorbox when it is displayed in a browser but not when it is displayed in a phone / tablet.

    I have used the concept of an answer from this very post (https://stackoverflow.com/a/23431190/260665) but made few modifications:

    /**
     * Raj: Used basic source from here: https://stackoverflow.com/a/23431190/260665
     **/
    
    // Make sure the options are sorted in descending order of their breakpoint widths
    var cboxDefaultOptions = 
            [   
                {
                    breakpointMinWidth: 1024,
                    values: {
                        width : '70%',
                        maxWidth : '700px',
                    }
                },
                {
                    breakpointMinWidth: 640,
                    values: {
                        width : '80%',
                        maxWidth : '500px',
                    }
                },
                {
                    breakpointMinWidth: 320,
                    values: {
                        width : '95%',
                        maxWidth : '300px',
                    }
                }
            ];
    
    $(window).resize(function(){
    //  alert (JSON.stringify($.colorbox.responsiveOptions));
    //  var respOpts = $.colorbox.attr('responsiveOptions');
        var respOpts = $.colorbox.responsiveOptions;
        if (respOpts) {
            var breakpointOptions = breakpointColorboxOptionsForWidth (window.innerWidth);
            if (breakpointOptions) {
                $.colorbox.resize({
                    width: window.innerWidth > parseInt(breakpointOptions.values.maxWidth) ? breakpointOptions.values.maxWidth : breakpointOptions.values.width,
                  });
            }
        }
    });
    
    function breakpointColorboxOptionsForWidth (inWidth) {
        var breakpointOptions = null;
        for (var i=0; i= anOption.breakpointMinWidth) {
                breakpointOptions = anOption;
                break;
            }
        }
        return breakpointOptions;
    }
    

    Usage:

            $.colorbox.responsiveOptions = cboxDefaultOptions;
    

    When the colorbox object is prepared just add this additional attribute to it. We can also configure cboxDefaultOptions or supply a different custom valued object to $.colorbox.responsiveOptions so that it loads with different breakpoints if needed.

提交回复
热议问题