我想根据页面是否提供不同的内容 在大屏幕(PC/平板电脑)或小屏幕(手机)上查看。 我的网站是响应式的,使用bootstrap,但是我有很多内容,只适合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.html
和 desktop.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/