gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:59:42 24 4
gpt4 key购买 nike

在下面的示例中,我使用@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 访问 smaller 布局的 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

最佳答案

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

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

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

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

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

有关 styleSheet 的更多信息对象,参见 http://www.javascriptkit.com/domref/stylesheet.shtml

关于jquery - 无论屏幕分辨率如何,都使用 jQuery 访问@media css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6474404/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com