无论屏幕分辨率如何,都使用jQuery访问@media css属性

时间:2011-06-24 22:28:55

标签: jquery css

在下面的示例中,我使用@media查询来调整屏幕分辨率更改时“布局”的大小。

/* styles for small screen and preview */
@media only screen and (min-width: 600px) {
    #layout { width: 500px; height: 500px; }
}

/* styles for large screen */
@media only screen and (min-width: 900px) {
    #layout { width: 800px; height: 800px; }
}

一切都运行得很好,但我还想使用jQuery访问较小布局的css属性来创建它的预览。因为预览需要一些操作(例如,它将是原始高度和宽度的较小百分比),我想使用jQuery以编程方式计算预览的尺寸(而不是简单地硬编码)。

所以我的问题是,有没有办法使用jQuery访问较小版面的css属性,无论屏幕分辨率如何?

注意:上面的例子简化了我在更广泛的用例中需要做的事情,所以我很清楚需要这个。我还需要为不同的布局(每个都有自己的样式表)执行这么多次,所以理想情况下需要一种编程方式来执行此操作。

非常感谢任何帮助!

修改

为了兴趣,我在Björn的建议中附上了一个例子。可能有更优雅的方法,但它适用于我。

<html>
<head>
<title>Example: accessing @media css properties</title>
<style>
/* default styles for tiny screen */
#preview { background: #ccf; }
#layout  { width: 300px; height: 300px; background: #eee; }

/* styles for small screen and preview */
@media only screen and (min-width: 600px) {
    #layout { width: 500px; height: 500px; background: #cdf; }
}

/* styles for large screen */
@media only screen and (min-width: 900px) {
    #layout { width: 800px; height: 800px; background: #ffc; }
}
</style>
<script src="jquery.js"></script>
<script>
$(function() {
    // first style sheet in page (only one in this example)
    var styles = document.styleSheets[0]; 

    for (i=0;i<styles.cssRules.length;i++) {
        theRules = styles.cssRules[i];
        // type 4 = media rules; media.mediaText = we can pick the media styles we want
        if (theRules.type == 4 && theRules.media.mediaText == 'only screen and (min-width: 600px)') {
            // media rules have their own cssRules collection
            // cssRules[0] = the first rule, i.e. #layout
            var layoutwidth = theRules.cssRules[0].style.width;
            var layoutheight = theRules.cssRules[0].style.height;
            var previewscale = 5;           
            var previewwidth = Math.round(parseInt(layoutwidth )/previewscale);
            var previewheight = Math.round(parseInt(layoutheight)/previewscale);
            // now I can set my preview dimensions      
            $('#preview').width(previewwidth).height(previewheight);            
            console.log('Preview dimensions: ' + previewwidth + ' x ' + previewheight);
        }
    }

});         
</script>
</head>
<body>
<div id="layout">layout
    <div id="preview">preview</div>
</div>
</body>
</html>

控制台将显示:

预览尺寸:100 x 100

1 个答案:

答案 0 :(得分:1)

您可以通过document.stylesheets对象访问文档的样式表。

例如,这将输出页面上第一个样式表中找到的第一个css规则:

console.log(document.styleSheets[0].cssRules[0].cssText);

您可以在这些对象上使用正则表达式或其他内容来获取所需声明的规则集(一旦确定了声明了哪个文档的styleSheet对象),并将这些规则应用于新创建的styleSheet ($("<style />")应该有用。

我不太确定你将如何预览较小的版本,所以我不清楚如何将这个新的样式表应用到预览中,但我希望这足以让你开始。

有关styleSheet对象的详细信息,请参阅http://www.javascriptkit.com/domref/stylesheet.shtml