通过手机和浏览器上的屏幕方向实现不同的javascript/jQuery功能 [英] different javascript/jQuery function by screen orientation on mobile AND browser

查看:60
本文介绍了通过手机和浏览器上的屏幕方向实现不同的javascript/jQuery功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我不是javascript或jQuery专家.

Disclaimer: I am not a javascript or jQuery expert.

这可能是一个容易解决的问题,因为这只是我不知道的小问题.我正在实现一个网站,如果浏览器为横向模式,则该网站为水平;如果为纵向,则为垂直. CSS更改不是问题,因为使用媒体查询很容易.我遇到的问题是,当我只想在屏幕处于横向模式时才运行特定的脚本.我遇到的下一个问题是,我不仅希望它能在移动设备上运行,而且还希望它在标准浏览器中也能响应.即检测屏幕宽度>屏幕高度的时间,然后运行上述脚本.到目前为止,这是我的代码:

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

此功能可以很好地检测页面加载时的方向,但是由于脚本未绑定到window.resize,因此在调整屏幕大小时它不会改变.话虽如此,当我将其绑定到window.resize时,它也不起作用.

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?

推荐答案

万一将来有人遇到这个问题,我将发布解决我问题的方法.

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

这篇关于通过手机和浏览器上的屏幕方向实现不同的javascript/jQuery功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆