我正在尝试根据其宽度将一个类添加到特定的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> 414像素宽时,要添加.wide到.v65-productGroup-product中,我需要更改什么?
答案 0 :(得分:0)
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像素时更改它,则需要使用数学技巧来计算窗口的宽度,必须从这些值之一加上余下的宽度和比例因素(您知道的是微调元素)来计算窗口的宽度
答案 1 :(得分:0)
也许这支笔有帮助:
https://codepen.io/anon/pen/zQXMoz
我基本上修改了您所指的笔,并添加了想要的功能。更改页面大小以查看效果。
P.S。在您自己的代码中,您的意思是:
if (width < 414) {
代替
if (width < 141) {
?
此外,如果您只想在414px
上切换课程,则该课程就足够了:
if (width < 414) {
// remove class
}
else {
// add class
}
答案 2 :(得分:0)
我做了这个演示:在全页视图中查看它并更改浏览器宽度
"use strict";
console.clear();
const addWideClass = function() {
Array.from(document.getElementsByTagName('span')).forEach(el => {
const w = el.offsetWidth
el.style.setProperty('--w', `'${w}'`);
if (w < 141) {
el.classList.remove("wide");
} else if (w >= 415) {
el.classList.add("wide");
}
})
};
window.addEventListener('resize', addWideClass)
addWideClass()
div {
display: flex;
}
div span {
box-sizing: border-box;
padding: 10px;
--w: '213232';
}
div span:nth-child(1) {
flex-grow: 2;
flex-basis: 0;
background-color: gold;
}
div span:nth-child(2) {
flex-grow: 3;
flex-basis: 0;
background-color: silver;
}
div span:nth-child(3) {
flex-grow: 4;
flex-basis: 0;
background-color: goldenrod;
}
div span.wide {
border: 10px solid #000;
}
div span:before {
content: var(--w);
display: block;
}
<div>
<span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempora similique vitae accusantium repellat nobis architecto unde, exercitationem soluta placeat voluptatum nostrum beatae tenetur ad deleniti voluptate quia quis officia voluptatem.</span>
<span>At ex velit eligendi ipsam doloribus doloremque laudantium, minus mollitia dicta quis sit nostrum commodi incidunt autem provident vero! Rem distinctio, optio harum deserunt aperiam corporis. Quod maxime eos porro!</span>
<span>Quaerat, quo adipisci voluptas dolores odio maxime maiores obcaecati repellendus ducimus a cupiditate placeat, fugiat nostrum distinctio quidem nemo rem error laborum ipsam eos dicta corrupti. Nobis iure suscipit saepe.</span>
</div>
P.S。您可能要考虑对resize事件进行防抖(我将防抖延迟时间设置为一秒钟,以使效果更明显。您宁愿要100毫秒之类的防抖延迟)
"use strict";
console.clear();
const addWideClass = function() {
Array.from(document.getElementsByTagName('span')).forEach(el => {
const w = el.offsetWidth
el.style.setProperty('--w', `'${w}'`);
if (w < 141) {
el.classList.remove("wide");
} else if (w >= 415) {
el.classList.add("wide");
}
})
};
// From: https://davidwalsh.name/javascript-debounce-function
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
window.addEventListener('resize', debounce(addWideClass, 1000))
addWideClass()
div {
display: flex;
}
div span {
box-sizing: border-box;
padding: 10px;
--w: '213232';
}
div span:nth-child(1) {
flex-grow: 2;
flex-basis: 0;
background-color: gold;
}
div span:nth-child(2) {
flex-grow: 3;
flex-basis: 0;
background-color: silver;
}
div span:nth-child(3) {
flex-grow: 4;
flex-basis: 0;
background-color: goldenrod;
}
div span.wide {
border: 10px solid #000;
}
div span:before {
content: var(--w);
display: block;
}
<div>
<span>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempora similique vitae accusantium repellat nobis architecto unde, exercitationem soluta placeat voluptatum nostrum beatae tenetur ad deleniti voluptate quia quis officia voluptatem.</span>
<span>At ex velit eligendi ipsam doloribus doloremque laudantium, minus mollitia dicta quis sit nostrum commodi incidunt autem provident vero! Rem distinctio, optio harum deserunt aperiam corporis. Quod maxime eos porro!</span>
<span>Quaerat, quo adipisci voluptas dolores odio maxime maiores obcaecati repellendus ducimus a cupiditate placeat, fugiat nostrum distinctio quidem nemo rem error laborum ipsam eos dicta corrupti. Nobis iure suscipit saepe.</span>
</div>