-->

best way to implement an overlay with pjax

2019-04-15 01:19发布

问题:

Currently I'm using pjax to load in a fragment and overlay the main page of my site page. I am then changing the body class with jquery to allow a few styling changes. This is fine but the browser back button doesn't work as it should due the body class change being triggered on click of the pjax trigger and therefor the body maintains the class of the overlay.

The effect I'm looking for is quite similar to this site when you click on a project.

http://www.watsonnyc.com/

Obviously this isn't working so there must be a better way of doing it.

Here is an example of my code:

$('.back').pjax('.info_overlay', { fragment: '.info_overlay',}).live('click', function(){
    $('body').removeClass("info").addClass("work");
    $('.info_overlay')
    .bind('pjax:start', function() { $(this).fadeOut(duration); })
    .bind('pjax:end', function() { $(this).hide(); });    
})

回答1:

Try to make it a simple PJAX request with beforeSend and complete attributes.

The beforeSend attribute will be executed before the http request is fired. I use it often when making a loader for a certain AJAX/PJAX event. Whenever the user fires the event (i.e. clicks a button), the function, assigned to beforeSend, hides the content of the div that I am updating and places a gif loader there, which gives a nice user experience.

The complete attribute will be executed after the requested page loads. If I use the example I gave with the loader, you can make the function, assigned to the complete attribute, hide the loader image and update the div with the loaded content from the requested page.

Here is an example with the loader image:

$.pjax({
    url: 'requested_page.php',
    container: '#updated_div',
    beforeSend: function(){
        $('#loader_place').fadeIn('normal'); // This will fade in a hidden div with fixed centered position
    },
    complete: function(){
        $('#loader_place').fadeOut('normal'); // This will fade out the div and make it invisible again
    }
});

If you want to do something more complicated, I suggest you read the PJAX Documentation.