如何在JavaScript中使用媒体查询

我对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'); } }); }); 

});

 $(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类何时可见:

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

然后只需检查JS该元素是否可见:

 if ($('.resolution-check').is(':visible')) { // do stuff here } 

这样,您就可以在CSS中的一个位置控制媒体查询

 function checkMatchMedia(pQuery) { if (!window.matchMedia) {return false;} if (window.matchMedia(pQuery).matches) {return true;} return false; } var vIsOK = checkMatchMedia("(min-width: 500px)"); if (vIsOK) { console.log('window width is at least 500px'); } else { if (window.matchMedia) { console.log('window width is less then 500px'); } else { console.log('Please include Polyfill.'); } } 

这只有一个小问题,那就是旧的IE不支持这个。

这通过添加名为polyfill的库来修复。

你确实在JS中有类似于媒体查询的东西:

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

如何在JavaScript中使用媒体查询并在移动设备上替换div或图像或文本Proto Theme Logo Change

 jQuery(function($){ if (window.matchMedia("(max-width: 500px)").matches) { $( ".vc_responsive .logo > a > img " ).replaceWith( "" ); } });