在 window 调整大小时借助对象键更新变量数据
Update variable data with the help of object key on window resize
最近我正在尝试创建像 swiperjs 这样的滑块。
这是我的代码
let config = {
perItem: 4,
breakpoints: {
992: {
perItem: 3
}
768: {
perItem: 2
}
}
}
let perItem = config.perItem
但是我卡在断点了。我想根据断点更新 perItem。
如何在纯 javascript.
中实现这一点
需要使用resize
事件监听器,然后循环config.breakpoints
找到对应的key:
let config = {
perItem: 4,
breakpoints: {
992: {
perItem: 3
},
768: {
perItem: 2
}
}
}
let perItem = config.perItem
window.addEventListener("resize", () => {
var keys = Object.keys(config.breakpoints).sort((a, b) => a - b);
for (var i = 0; i < keys.length; i++) {
if (window.innerWidth < keys[i]) {
perItem = config.breakpoints[keys[i]].perItem;
break;
}
}
document.querySelector('#perItem').innerHTML = `perItem is now ${perItem}`
});
<div id="perItem">Initial perItem is 4</div>
好吧,经过几次实验,我解决了这个问题。
这是解决方案
html
<div id="perItem">Initial perItem is 4</div>
js
let config = {
perItem: 4,
breakpoints: {
992: {
perItem: 3
},
768: {
perItem: 2
}
}
}
let perItem = config.perItem
window.addEventListener('resize', (e) => {
let array = []
for (const width in config.breakpoints) {
if (window.innerWidth < parseFloat(width)) {
array.push(width) // store widths into array
perItem = Math.floor(config.breakpoints[array[0]].perItem)
} else {
perItem = Math.floor(config.perItem)
}
}
document.querySelector('#perItem').innerHTML = `perItem is now ${perItem}`
})
如果有人想帮我在滑块中添加更多功能,那么这里是 github link
最近我正在尝试创建像 swiperjs 这样的滑块。 这是我的代码
let config = {
perItem: 4,
breakpoints: {
992: {
perItem: 3
}
768: {
perItem: 2
}
}
}
let perItem = config.perItem
但是我卡在断点了。我想根据断点更新 perItem。 如何在纯 javascript.
中实现这一点需要使用resize
事件监听器,然后循环config.breakpoints
找到对应的key:
let config = {
perItem: 4,
breakpoints: {
992: {
perItem: 3
},
768: {
perItem: 2
}
}
}
let perItem = config.perItem
window.addEventListener("resize", () => {
var keys = Object.keys(config.breakpoints).sort((a, b) => a - b);
for (var i = 0; i < keys.length; i++) {
if (window.innerWidth < keys[i]) {
perItem = config.breakpoints[keys[i]].perItem;
break;
}
}
document.querySelector('#perItem').innerHTML = `perItem is now ${perItem}`
});
<div id="perItem">Initial perItem is 4</div>
好吧,经过几次实验,我解决了这个问题。 这是解决方案
html
<div id="perItem">Initial perItem is 4</div>
js
let config = {
perItem: 4,
breakpoints: {
992: {
perItem: 3
},
768: {
perItem: 2
}
}
}
let perItem = config.perItem
window.addEventListener('resize', (e) => {
let array = []
for (const width in config.breakpoints) {
if (window.innerWidth < parseFloat(width)) {
array.push(width) // store widths into array
perItem = Math.floor(config.breakpoints[array[0]].perItem)
} else {
perItem = Math.floor(config.perItem)
}
}
document.querySelector('#perItem').innerHTML = `perItem is now ${perItem}`
})
如果有人想帮我在滑块中添加更多功能,那么这里是 github link