我对 JavaScript 知之甚少,甚至一无所知,所以我什至不确定我的问题是否有意义。然而,我的观点是如何应用媒体查询的相同原理来根据屏幕宽度更改脚本上的特定值。
在下面的示例中,我使用滚动 spy 事件菜单和 -100 像素的负滚动来补偿标题。此偏移量是必需的,因为 header 具有固定位置。
如果窗口小于 900px 宽度,我需要将偏移值更改为 0px,因为此时,Header 位置变为相对位置。
$(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;
}
}
});
});
最佳答案
您实际上确实有类似于 JS 中的媒体查询的东西:
if (matchMedia("(min-width: 900px)").matches) {
// the viewport is at least 900 pixels wide
}
关于javascript - 如何在 JavaScript 中使用媒体查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28111826/