如何在JavaScript中使用媒体查询 [英] How to use Media Queries in JavaScript

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

问题描述

我对JavaScript了解甚少,甚至不知道我的问题是否有意义。然而,我的观点是如何应用媒体查询的相同原理来根据屏幕的宽度更改脚本上的特定值。

I know little to nothing about JavaScript so I'm not even sure if my question makes sense. My point however is how to apply the same principle of media queries to change particular values on a script depending on the width of the screen.

在下面的示例中, m使用滚动间谍活动菜单,负面滚动-100px用于标题补偿。这个偏移是必要的,因为标题有固定的位置。

In the following example, I'm using a scroll spy active menu with a negative scrolling of -100px for Header compensation. This offset is necessary because the header has a fixed position.

如果窗口小于900px宽度,我需要偏移值更改为0px,因为在那一点,位置变得相对。

I need the offset value to change to 0px if window is smaller then 900px width, because at that point, Header position becomes relative.

$(document).ready(function () {
$(window).scroll(function () {

    var y = $(this).scrollTop();

    $('.link').each(function (event) {
        if (y >= $($(this).attr('href')).offset().top - 100) {
            $('.link').not(this).removeClass('active');
            $(this).addClass('active');
        }
    });

});

});

$(function () {
$('a[href*=#]:not([href=#])').click(function () {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        if (target.length) {
            $('html,body').animate({
                scrollTop: (target.offset().top - 100)
            }, 850);
            return false;
        }
    }
});

});

推荐答案

可以在css中定义 .resolution-check 类:

You can define .resolution-check class in css when to be visible:

@media only screen and (max-width: 900px) {
  .resolution-check {
    display: block;
  }
}

if ($('.resolution-check').is(':visible')) {

  // do stuff here

}

可以在一个位置(CSS

This way you can control media queries in one place, in CSS

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

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