调整函数大小并更改我的类的 CSS 值(在 JavaScript 中)



我尝试编写一个脚本来更改一个css,但前提是if中的条件为真。我不明白为什么我的脚本不起作用(即使我将其粘贴到浏览器控制台中(

$(document).load($(window).bind("resize", function () {
if (window.matchMedia('(min-width: 767px)').matches && window.matchMedia('(max-width: 1259px)').matches) {
$('.filter--facet-container').each(function () {
if ($(this).children().length >= 3 && $(this).children().length <= 4) {
$(".listing--actions.filter--container-additional").css("height", "125px");
}
})
}
}));
document

没有load事件,请注意没有任何反应:

$(document).load(function() {
console.log("Ran");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

你可能的意思是$(window).load(function(){ ... })

$(window).load(function() {
console.log("Ran");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

。但请注意,该事件发生在页面加载周期的后期,即加载所有资源(包括所有图像(之后。

要在 DOM 完成但在load事件之前运行代码,只需将代码放在文档末尾的script标记中,就在结束</body>标记之前(或使用 jQuery 的$(function() { })"DOM 就绪"功能,尽管实际上并不需要它(。


其他一些注意事项:

  1. bind已过时且已弃用。使用现代 jQuery(希望您使用的是现代版本(,请使用on.

  2. matchMedia返回一个对象,其中包含规则结果更改时的事件,因此无需使用resize

  3. matchMedia允许"和",无需进行两次单独的检查。

相反,对于仅反应性检查:

<script>
matchMedia("(max-width: 767px) and (max-width: 1259px)").addListener(function(e) {
if (e.matches) {
// Your .filter--facet-container logic here
}
});
</body>
</html>

或者对于初始主动检查,然后进行被动检查(可能是您想要的(:

<script>
(function() { // Avoid creating globals
var matcher = matchMedia("(max-width: 767px) and (max-width: 1259px)");
function facetContainerLogic() {
// Your .filter--facet-container logic here
}
// Proactive initial check
if (matcher.matches) {
facetContainerLogic();
}
// Get notifications when it changes
matcher.addListener(function(e) {
if (e.matches) {
facetContainerLogic();
}
});
})();
</body>
</html>

最新更新