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

查看:32
本文介绍了使用 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.

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

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 的值.也就是说,大于1000px宽"的规则可以设置一个隐藏的<div>为width: 1000px",然后你可以检查

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天全站免登陆