【问题标题】:Change Css File Depending On Browser Height根据浏览器高度更改 Css 文件
【发布时间】:2011-12-03 16:50:01
【问题描述】:

我可以根据浏览器的高度更改加载哪个 CSS 文件吗?

例如,如果浏览器小于 600px,则使用 index_sm.css,否则使用 index_lg.css。

【问题讨论】:

  • 您是否要查看用户是否在移动设备上?
  • 不,我的页面底部有一个页脚,它位于绝对底部 0,但如果屏幕太小,它会与页面内容重叠,所以当屏幕较小时,我将页脚从顶部

标签: css window


【解决方案1】:

在您的 <head> 标签中,输入以下内容:

<script type="text/javascript">
    if (window.innerHeight <= 600) {
        loadcss('index_sm.css');
    } else {
        loadcss('index_lg.css');
    }

    function loadcss(file) {
        var el = document.createElement('link');
        el.setAttribute('rel', 'stylesheet');
        el.setAttribute('type', 'text/css');
        el.setAttribute('href', file);
        document.getElementsByTagName('head')[0].appendChild(el);
    }
</script>

【讨论】:

  • 请注意,这仅在启用 Javascript 时才有效,因此如果有人使用 noscript 或从禁用 javascript 的浏览器浏览,它将不起作用。
  • 屏幕高度不是浏览器高度
  • 我刚刚意识到这在 IE 中不起作用,当我输入警报时,我得到“未定义”。有什么想法吗?
  • 你应该检查用户代理并使用document.body.offsetHeight(或document.documentElement.offsetHeight)作为IE。
【解决方案2】:

这是我能想到的最佳答案,我终于在一个非常有用的网站上偶然发现了这个。

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

网站是:http://css-tricks.com/6206-resolution-specific-stylesheets/

jQuery 会即时更改浏览器的 css,因此如果您调整浏览器的大小,css 也会发生变化。它也适用于所有浏览器。

【讨论】:

  • +1 很好的解决方案。它使用 jQuery,因此可以解决跨浏览器问题。
【解决方案3】:

supporting browsers 中,您可以使用media queries(特别是height media feature)。

【讨论】:

  • 从我链接到的部分:“接受最小/最大前缀:是”,所以只需使用 max-heightmin-height
【解决方案4】:

正如昆汀所说,您可以使用媒体查询。但是,我认为您已经拥有 n 个 css 文件,并且想要即时选择其中一个。只需在文档头中使用类似的内容即可。

<script language="text/javascript">
if (screen.width == 640) {
  document.write('<link rel="stylesheet" type="text/css" href="640.css">');
}
else if (screen.width == 800) {
  document.write('<link rel="stylesheet" type="text/css" href="800.css">');
}
</script>

【讨论】:

  • 屏幕高度和浏览器高度是不同的东西。
  • 抱歉。你说的对。使用 window.innerWidth 和 window.innerHeight 而不是 screen.width 和 screen.height。或者在 jQuery 中 $(window).width() 和 $(window).height();
猜你喜欢
  • 2012-06-02
  • 2013-11-21
  • 2021-01-27
  • 2013-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
相关资源
最近更新 更多