let size = carousel_images[0].clientWidth;我使用和在不同視口中變化來獲取幻燈片圖像的大小clientWidth,這里,carousel_images是指向img內的.carousel,這里是它在不同視口中的變化方式:@media screen and (min-width: 1024px) { .carousel { max-width: 994px; img { min-width: 994px; } }}@media screen and (min-width: 1200px) { .carousel { max-width: 1150px; img { min-width: 1150px; } }}所以當我調整瀏覽器大小時,它看起來像:但當我刷新頁面時,它看起來又正常了。這是完整的代碼筆鏈接,謝謝。
2 回答

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

江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
我認為你必須為你的let size
.?它是全局變量嗎?也許,將其放入函數或類中是一個好主意。
您可以使用調整大小事件,該事件在窗口大小更改時觸發。
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>
- 2 回答
- 0 關注
- 164 瀏覽
添加回答
舉報
0/150
提交
取消