Vertical align using jquery for all devices?

2019-03-31 23:23发布

问题:

I found as problematic thing to align vertically some elements on page, without changing some others elements layouts.

The problem is magnified on mobile devices. So many screen sizes, resolutions, portrait, landscape...

var x=window.innerHeight - $('#myDiv').height();
    $('#myDiv').css ('margin-top', x/2);

This should be ok for all devices, mobile and desktop. Do you see any downside of these approach?

As I understand, all devices today support JavaScript. But, is it possible that some device supports JS but doesn't support jQuery ?

回答1:

You should use $('#myDiv').parent().height() instead of window.innerHeight, Because if your #myDiv element was wrapped by another element, your approach may not work correctly.
Also you can encapsulate your codes into a jQuery plugin, like this:

jQuery.fn.verticalAlign = function ()
{
    return this
            .css("margin-top",($(this).parent().height() - $(this).height())/2 + 'px' )
};

Then you can use it like:

$('#myDiv').verticalAlign();

is it possible that some device support JS but doesn't support jQuery ? No, All devices that support a proper version of JS must sopport jQuery, Because the core of jQuery is pure JS
But if you want to align your element vertically in browser screen, You may use the following instead:

jQuery.fn.verticalAlignScreen = function ()
{
    return this
            .css("position", "absolute")
            .css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px");
};


回答2:

JQuery - is the same JavaScript! It's just a container with pre-written functions that you can use ( framework ). So if JS works - JQ works. But diferrences on mobile devices are in Java Script engines. I can tell that Safari JS engine is better than Google, which means you're Web Application will run faster on iOS



回答3:

Actually, if you know the height of your div, than you can you just use pure css,For example i have popup,that has height 540px. To align it vertically on all different devices, i would use:

.popup{
  top:50%;
  margin-top:-270px;
}

The same is with horizontal alignment. Only there you use another styling. For example your div has 480px width:

.popup{
   left:50%
   margin-left:-240px;
 }

Another way to approach vertical alignment, if you dont know the height, and do not want to care about that, is following jquery methode:

    var a =  Math.round( $(".popup").height()/2 );//here we get half of our divs height
    $(".window_popup").css("margin-top", ( - a  + "px" ) );//here we give to  
   //variable negative  value and get necessary result :)