简体   繁体   English

页面重定向不适用于移动设备

[英]Page Redirect Not Working for mobile device

I have the following code that doesn't redirect when a mobile device accesses the web page. 我有以下代码,当移动设备访问网页时,这些代码不会重定向。 Where I'm I going wrong? 我要去哪里了?

 <!DOCTYPE html> <html> <head> <script type="text/javascript"> var bodyclass = $('body').is('.index'); if ((screen.width <= 800) && (bodyclass = true)) { window.location = "m/index.html"; } </script> <title>screen stest</title> </head> <body class="index"> <div class="style"> <h1>index try10000</h1> </div> </body> </html> 

There are a couple of things, first are you sure your device is <= 800px width? 有两件事,首先您确定您的设备的宽度<= 800px吗? Second your script is being loaded in the head and blocks the loading of the remaining DOM structure. 其次,您的脚本正在头部加载,并阻止其余DOM结构的加载。 As you have code that relies on the DOM being loaded you need to defer the execution of your script until the DOM is loaded. 由于您的代码依赖于正在加载的DOM,因此需要将脚本的执行推迟到DOM被加载之前。 Wrap you code in a DOM ready function (example using jQuery). 将代码包装在DOM ready函数中(使用jQuery的示例)。

$(function() {
    var bodyclass = $('body').is('.index');

    if ((screen.width <= 800) && (bodyclass = true)) {
        window.location = "m/index.html";
    }
});

Or better yet, just move your script to be the last element of the body. 或者更好的是,只需将脚本移动到正文的最后一个元素即可。 Then there is no need for a DOM ready wrapper. 这样就不需要DOM ready包装器了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM