Vertical align using jquery for all devices?

孤者浪人 提交于 2019-12-03 20:20:03

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");
};

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

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 :)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!