我想要使??用 react.js 滾動時的影像影片效果,類似于:https ://www.roche.com/ 我有這個代碼:
<ArticleWrapper >
<img className='image' src={Img} alt='Image' />
</ArticleWrapper >
我希望在img向下滾動時加寬影片并在向上滾動時恢復正常!謝謝。
uj5u.com熱心網友回復:
帶有可運行示例的可能解決方案之一
這是做到這一點的方法之一:
- 用一個填充的和以 flex 為中心的容器包裹你的 img
- 為您的 img 提供 width: 100% 以適合容器
- 給你的容器一個填充(讓你的影像在開始時變得像你想要的那樣小)
- 設定滾動監聽器
- 為影像容器計算新的填充值
- 使用新的填充值更新容器
在片段中,我有 2 個重要變數:
maxPadding填充值(更高 = 更小的 img)maxScrollFor100滾動完成的點(以 px 為單位)又名大 img
這里我們有可運行的代碼片段
const maxScrollFor100 = 300; // Y Scroll Point where the image should be 100% width
const maxPadding = 100; // Initial pagging of the container (should be equal to the initial padding
const imgContainer = document.getElementById('img-container');
imgContainer.style.padding = '0 ' maxPadding 'px';
window.addEventListener('scroll', function(event) {
// Get the current scrollY point
const sY = window.scrollY;
// Get a padding percentage (we want 100% with 0 scroll and 0% with 300 or scroll)
const percent = 100 - (sY >= maxScrollFor100 ? 100 : sY / (maxScrollFor100 / 100));
// console.log("Actual Percent Zoom", percent.toFixed(1)); // Show the current zoom percentage.
// Compute the new padding value
const padding = maxPadding * (percent / 100);
// Update the dom with the new padding for the image container
imgContainer.style.padding = '0 ' padding 'px';
}, {passive: true})
.flex-center {
display: flex;
justify-content: center;
align-items: center;
}
<div style="padding-top: 150px">
<div id="img-container" class="flex-center">
<img src="http://www.pixolo.it/wp-content/uploads/2012/11/stones-and-sea-1920x1200-wallpaper-6620.jpg" width="100%" />
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/494819.html
標籤:javascript 反应
