如何在 JavaScript 中使用媒体查询

Dav*_*ins 2 javascript css jquery scroll media-queries

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

在下面的示例中,我使用滚动间谍活动菜单,并使用 -100px 的负滚动来进行标题补偿。此偏移是必要的,因为标头具有固定位置。

如果窗口小于 900px 宽度,我需要将偏移值更改为 0px,因为此时,标题位置变得相对。

$(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');
        }
    });

});
Run Code Online (Sandbox Code Playgroud)

});

$(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;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

});

Ben*_*ock 5

实际上,JS 中确实有类似媒体查询的东西:

if (matchMedia("(min-width: 900px)").matches) {
  // the viewport is at least 900 pixels wide
}
Run Code Online (Sandbox Code Playgroud)