我想根据网页是否提供不同的内容
在大屏幕(PC /平板电脑)或小屏幕(移动设备)上查看。
我的网站使用引导程序响应迅速,但是我有很多内容,仅适用于PC。它完全淹没了移动阅读器。

当网站位于以下位置时,如何提供不同的段落和图像内容
在较小的屏幕上观看?

有人建议我使用javascript或(更糟糕的)媒体查询,但我不知道如何。
我是新来的-您能提供一些示例代码吗?

谢谢

注意1:这不是(只是)样式表问题。而不是渲染
相同的内容采用不同的格式,我想发送不同的内容。

注意2:我不想开发一个新的.mobi网站,该网站将会丢失
我现有的搜索引擎声誉。

最佳答案

您应该看一下它,它与您要实现的目标非常相似:Prevent a video background from being downloaded on mobile browsers

您可以使用以下代码来检测移动设备:

function detectmob() {

    if( navigator.userAgent.match(/Android/i)
    || navigator.userAgent.match(/webOS/i)
    || navigator.userAgent.match(/iPhone/i)
    || navigator.userAgent.match(/iPad/i)
    || navigator.userAgent.match(/iPod/i)
    || navigator.userAgent.match(/BlackBerry/i)
    || navigator.userAgent.match(/Windows Phone/i)
    ){

        // If mobile, then we do all this

    }
    else {

        // If not mobile then do this

    }
} // detectmob


---------- [编辑] ----------

var width = window.innerWidth;
var height = window.innerHeight;

if (width  > 480) {
    // Mobile code
} else {
    // Other code
}


---------- [编辑] ----------

创建两个文件mobile.htmldesktop.html,并为它们提供适当的内容。
然后,在您的主页中,将以下JavaScript放在页面底部:

function getFileContent(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                var fileContent = rawFile.responseText;
                document.getElementsByTagName("body")[0].innerHTML = fileContent;
            }
        }
    }
    rawFile.send(null);
}


现在,您可以根据访问者是在手机上还是在计算机上,使用以前的javascript获取文件内容并显示它们:

var width = window.innerWidth;
var height = window.innerHeight;

if (width  > 480) {
    // Mobile code
    getFileContent("mobile.html");
} else {
    // Other code
    getFileContent("desktop.html");
}


就是这样!如果您需要其他帮助,请告诉我。

关于javascript - 如何根据屏幕尺寸发送不同的内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31882018/

10-10 22:08
查看更多