使用CSS媒体查询触发jQuery [英] Triggering jquery with css media queries

查看:137
本文介绍了使用CSS媒体查询触发jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目上使用css媒体查询来创建一个可与任何尺寸的屏幕一起使用的网站.我希望像使用CSS一样触发差异jquery函数.

I am using css media queries on my project to create a site that will work with any sized screen. I am looking to trigger difference jquery functions just like I would with css.

例如,如果浏览器的大小在1000像素到1300像素之间,我想调用以下函数:

For example, If the browser size is between 1000px and 1300px, I would like to call the following function:

$('#mycarousel').jcarousel({
    vertical: true,
    scroll: 1,
    auto: 2,
    wrap: 'circular'
});

但是,当浏览器大小小于1000px时,js将停止其处理.依此类推.

BUT when the browser size is below 1000px, the js would stop its processing. So on and so forth.

我不确定是否可行,但是也许有一个现有的解决方案或插件可以根据浏览器窗口大小创建不同的js环境.我想我可以用某种格式创建条件语句.有什么想法吗?

I'm not sure if this is possible, but perhaps there is an existing solution or plugin that creates different js environments based on browser window sizes. I suppose I could create conditional statements in some format. Any thoughts?

推荐答案

Modernizr 库支持进行直接JavaScript调用,评估媒体查询.

The Modernizr library supports making direct JavaScript calls that evaluate media queries.

如果您不想这样做,则可以让不同的CSS规则驱动隐藏元素的某些属性,然后可以使用".css()"从jQuery检查值.换句话说,大于1000像素宽"的规则可以将隐藏的<div>设置为宽度:1000像素",然后您可以检查

If you don't want to do that, you could have your different CSS rules drive some property of a hidden element, and you could then use ".css()" to check the value from jQuery. In other words, the rule for "bigger than 1000px wide" could set a hidden <div> to "width: 1000px", and you could then check

if ( $("#widthIndicator").css("width") === "1000px") {
  // whatever

此处是一个愚蠢的jsfiddle演示.左右拖动中间的分隔条,以查看JavaScript代码(在间隔计时器中)检测到隐藏元素的有效宽度"更改.

Here is a dumb jsfiddle demonstrating. Drag the middle separator bar left and right to see that the JavaScript code (in the interval timer) detects the change to effective "width" of the hidden element.

如果您引用的是响应式设计,则还可以触发现有元素的属性,而无需在html中添加标记,例如

If you refer to a responsive design then you could also trigger an existing element's property without adding markup to your html,for example

if ( $("#navigation li").css("float") === "none") {

这篇关于使用CSS媒体查询触发jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆