React操作真實DOM實現動態吸底部的樣本,reactdom
動態吸底:開始時fixed在頁面上,當頁面滾動到距離底部一定距離的時fixed部分固定。
這個是需要計算頁面滾動距離的,如果使用Jquery或者原生js實現是非常好實現的,但是由於使用react並不推崇操作DOM,但是如果使用virtual DOM的話是無法實現該效果的,所以還是要引入js去直接擷取DOM進行操作。
react在componentDidMount之後頁面渲染完成,所以可以在這裡面直接用js原生方法擷取DOM元素,進而進行操作。
componentDidMount() { this.changeFixed()}//計算高度changeFixed(){ //getDOMNode const layoutNode = document.querySelectorAll('.page-layout')[0]; const orderPriceNode = document.querySelectorAll('.test-price')[0]; window.addEventListener('scroll', function (e) { const windowInnerHeight = window.innerHeight; const layoutNodeHeight = layoutNode.offsetHeight; //滾動超出視野距離 let scrollTop = window.pageYOffset|| document.documentElement.scrollTop || document.body.scrollTop; const distanceBottom = layoutNodeHeight - scrollTop - windowInnerHeight; //120的時候吸底 if(distanceBottom <= 120){ orderPriceNode.classList.remove('fixed'); }else{ orderPriceNode.classList.add('fixed'); } })}
這樣就實現了當距離底部120的時候吸底
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。