Home>Article>Web Front-end> React operates the real DOM to achieve dynamic bottom sucking
This article mainly introduces the example of React operating real DOM to achieve dynamic bottom sucking. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
Dynamic bottom sucking: The fixed part is fixed on the page at the beginning, and when the page is scrolled to a certain distance from the bottom, the fixed part is fixed.
This requires calculating the scrolling distance of the page. It is very easy to implement if you use Jquery or native js. However, since using react does not recommend operating DOM, this effect cannot be achieved if you use virtual DOM. , so it is still necessary to introduce js to directly obtain the DOM for operation.
react completes page rendering after componentDidMount, so you can directly use js native methods to obtain DOM elements and then perform operations.
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'); } }) }
In this way, the bottom is sucked when the distance from the bottom is 120
Related recommendations:
Detailed examples explain the difference between empty and remove based on DOM
Examples share JQuery selector and DOM node operation exercises
js dom events Advanced Supplement
The above is the detailed content of React operates the real DOM to achieve dynamic bottom sucking. For more information, please follow other related articles on the PHP Chinese website!