different javascript/jQuery function by screen orientation on mobile AND browser

牧云@^-^@ 提交于 2019-12-24 01:54:26

问题


Disclaimer: I am not a javascript or jQuery expert.

This is probably an easy problem to solve, as it's just a small fix I can't figure out. I am implementing a site that is horizontal if the browser is in landscape mode, and vertical if in portrait. CSS changes are not an issue as that is easy with media queries. The problem I run into is when I want to only run a specific script when the screen is in landscape mode. Next problem I run into is that I don't just want this to work on mobile, but I also want it to be responsive in a standard browser as well; i.e. detect when the screen width > screen height and run said script. Here is my code so far:

var height = $(window).height();
var width = $(window).width();
if (width > height) {
    //run landscape script
} else {
    //run portrait script
};

This is working just fine to detect orientation when the page loads, but it doesn't change when the screen is resized since the script is not bound to window.resize. That being said, it is also not working when I bind it to window.resize.

Is there a better way to go about this? Or do I just need to fix up what is already here?


回答1:


In case somebody else runs into this problem in the future, I'll post what solved my problem.

When I attempted to add the resize event to the function, my code looked like this:

$(window).on('resize', function() {
    var height = $(window).height();
    var width = $(window).width();
    if (width > height) {
        //run landscape script
    } else {
        //run portrait script
    };
)};

This worked just fine, but it did not appear that way because the script was only being fired when the browser resized. While this is essential, the script also needs to fire when the page loads. My solution was just to add 'load' to the event:

$(window).on('resize load', function() {
    var height = $(window).height();
    var width = $(window).width();
    if (width > height) {
        //run landscape script
    } else {
        //run portrait script
    };
)};


来源:https://stackoverflow.com/questions/13882559/different-javascript-jquery-function-by-screen-orientation-on-mobile-and-browser

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