How do I use colorbox to show hidden divs on my page without hardcoding?

后端 未结 4 1937
情深已故
情深已故 2021-02-13 03:51

I\'m using Colorbox to show the html content of hidden divs on my page. I can get this to work perfectly with the following:

$(\"a.colorbox\").colorbox({width:\         


        
4条回答
  •  青春惊慌失措
    2021-02-13 04:10

    I didn't really like any of the answers given above. This is how I did it (similar but not quite the same). I also fully commented it for people a bit new to Javascript and the colorbox plug in.

    $(document).ready(function() { //waits until the DOM has finished loading
        if ($('a.lightboxTrigger').length){ //checks to see if there is a lightbox trigger on the page
            $('a.lightboxTrigger').each(function(){ //for every lightbox trigger on the page...
                var url = $(this).attr("href"); // sets the link url as the target div of the lightbox
                $(url).hide(); //hides the lightbox content div
                $(this).colorbox({
                     inline:true, // so it knows that it's looking for an internal href
                     href:url, // tells it which content to show
                     width:"70%",
                     onOpen:function(){ //triggers a callback when the lightbox opens
                        $(url).show(); //when the lightbox opens, show the content div
                     },
                     onCleanup:function(){
                        $(url).hide(); //hides the content div when the lightbox closes
                     }
                }).attr("href","javascript:void(0)"); //swaps the href out with a javascript:void(0) after it's saved the href to the url variable to stop the browser doing anything with the link other than launching the lightbox when clicked
                  //you could also use "return false" for the same effect but I proffered that way
            })
         }
    });
    

    And this is the html:

    Lightbox trigger
    

    Lightbox content goes here

    I think it would work with multiple lightboxes on the one page but I haven't tested it with that.

提交回复
热议问题