2 回答

TA貢獻1839條經驗 獲得超15個贊
您需要添加以下代碼:
window.addEventListener('resize', ()=>{
size = carousel_images[0].clientWidth
carousel_slide.style.transform = `translateX(${-size}px)`
})
本質上,您需要resize在使用該變量的任何位置監聽窗口事件、更新變量并再次執行代碼。

TA貢獻1804條經驗 獲得超8個贊
我認為你必須為你的let size. 是全局變量嗎?也許,將它放在函數或類中是個好主意。
您可以使用 resize 事件,該事件在您的窗口更改大小時觸發。
以下演示來自: https ://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event
const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');
function reportWindowSize() {
heightOutput.textContent = window.innerHeight;
widthOutput.textContent = window.innerWidth;
}
window.onresize = reportWindowSize;
<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>
添加回答
舉報