Home  >  Article  >  Web Front-end  >  React operates the real DOM to achieve dynamic bottom sucking

React operates the real DOM to achieve dynamic bottom sucking

小云云
小云云Original
2018-01-04 10:24:451681browse

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(&#39;fixed&#39;);
  }else{
   orderPriceNode.classList.add(&#39;fixed&#39;);
  }
 })
}

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn