我正在尝试根据其宽度将一个类添加到特定的 div,因此它会随着整个窗口(以及具有百分比宽度的 div)调整大小而动态添加或删除。
我试过使用 javascript querySelector 和 offsetWidth 来识别 div,但到目前为止它没有用。我的方法灵感来自 this codepen (它获取窗口宽度,与我尝试做的略有不同)。
这是我目前所拥有的:
var addWideClass = function() {
var width = document.querySelector('.v65-productGroup-product').offsetWidth;
if (width < 141) {
$('.v65-productGroup-product').removeClass('wide');
} else if (width >= 415) {
$('.v65-productGroup-product').addClass('wide');
};
};
$(window).resize(function(){
addWideClass();
});
addWideClass();
当 .v65-productGroup-product > 414px 宽时,我需要更改什么才能将 .wide 添加到 .v65-productGroup-product?
最佳答案
offsetWidth 可能被兑现或错过了回流。 Browser vendors may choose how to handle DOM calculations like offsetWidth .
如您所说:整个窗口(以及具有百分比宽度的 div)调整大小。您可以更改此行以检测窗口宽度而不是 div 宽度:
var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || screen.width
那么你可以拥有typical device breakpoints .如果您真的需要在 div 为 141 和 415 像素时更改它,则需要使用您的数学技能来计算窗口必须从这些值之一添加到您知道的相邻元素的其余宽度和概率因素的宽度.
关于javascript - 如何根据 div 宽度将类应用于 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56458196/