繁体   English   中英

如何使用jQuery或任何其他方法根据浏览器窗口的宽度动态加载不同的php文件

[英]how to load a diferrent php file dynamically based on the browser window's width using jQuery or any other method

您好朋友,这是一个非常新手的问题,因为我是编程的新手。

我正在浏览Web,发现了一种根据浏览器宽度动态加载CSS文件的方法。

jQuery的

function adjustStyle(width) {
    width = parseInt(width);
    if (width < 701) {
        $("#size-stylesheet").attr("href", "css/narrow.css");
    } else if ((width >= 701) && (width < 900)) {
        $("#size-stylesheet").attr("href", "css/medium.css");
    } else {
       $("#size-stylesheet").attr("href", "css/wide.css"); 
    }
}

$(function() {
    adjustStyle($(this).width());
    $(window).resize(function() {
        adjustStyle($(this).width());
    });
});

HTML

<link rel="stylesheet" type="text/css" href="main.css" />
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="narrow.css" />

我想知道,我可以使用相同的加载php file吗?

如果是的话代码是什么样的?

我想我们需要使用像<?php require_once('http://mysite.com/layouts/ipad.php'); ?> <?php require_once('http://mysite.com/layouts/ipad.php'); ?>但我如何编码呢?

请帮助。

问候

我想知道,我可以使用相同的加载php文件吗?

如果通过“加载一个php文件”你的意思是加载一个不同的页面,你将为不同的条件(宽度,等等)定义不同的页面,那么你可以通过设置window.location等于所需的页面来加载不同的页面。 这将用您指定的页面替换当前页面。

我不认为您每次每次调整窗口大小时都应该这样做。 如果必须这样做,则至少检查新大小是否确实需要更改,而不是反复进行重新加载。

以下内容与您现有的代码相似:

function setLocation(url) {
   if (window.location.href.indexOf(url) === -1)
      window.location = url;
}

function reloadPage(width) {
    width = parseInt(width);
    if (width < 701) {
        setLocation("yournarrowpage.php");
    } else if (width < 900) {
        setLocation("yourmediumpage.php");
    } else {
        setLocation("yourwidepage.php");
    }
}

$(function() {
   reloadPage($(this).width());
   $(window).resize(function() {
       reloadPage($(this).width());
   });
});

不过,您不必每次都重新加载整个页面,您可以使用Ajax仅重新加载某些部分。 为此,除了设置window.location之外,您可以使用类似于jQuery的.load() method

function setLocation(url) {
   $("selector for the element to reload").load(url);
}

我怀疑你真正想做的是根据浏览器或分辨率将用户重定向到不同的页面。

$(document).load(function() {
    var $width = $(window).width()
    if($width < 701)
        window.location = 'narrow.php'
    else if($width < 900)
        window.location = 'medium.php'
    else
        window.location = 'wide.php'
})

您可以轻松地使相同的函数在窗口调整大小上运行,尽管它可能不如您希望的那样工作。

编辑:如果你只是专门为iPad做这个(你不应该):

if(stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla/5.0(iPad;')) {
     // probably an iPad
     require('ipad.php');
     //Or maybe the below might serve you better:
     /*
     header('Location:ipad.php');
     die();
     */
}
 if (width < 701) {
    $.get('yourlayoutfor701.php', function(data) {
    $('#your_layout').html(data);  
    });
 }

希望这会对您有所帮助,但不是一个好习惯

暂无
暂无

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

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