窗口大小
在不同浏览器中确定浏览器窗口大小没有想象中那么容易。所有现代浏览器都支持 4 个属性:
- innerWidth
- innerHeight
- outerWidth
- outerHeight
outerWidth
和 outerHeight
返回浏览器窗口自身的大小(不管是在最外层 window 上使用,还是在窗格中使用)。
innerWidth
和 innerHeight
返回浏览器窗口中页面视口的大小(不包含浏览器边框和工具栏)。
document.documentElement.clientWidth
和 document.documentElement.clientHeight
返回页面视口的宽度和高度
什么时候显示置顶Icon
当滚动条位置-页面视口高度 > 0时
const [showIcon, setShowIcon] = useState(false);
useEffect(() => {
window.addEventListener("scroll", scroll);
}, [])
useEffect(() => {
return ()=> {
window.removeEventListener("scroll", scroll);
}
}, [])
const scrollToTop = () => {
document.body.scrollTop = document.documentElement.scrollTop = 0;
};
const scroll = e => {
let scroll = document.documentElement.scrollTop;
let screenHeight = document.documentElement.clientHeight;
if (scroll - screenHeight > 0)
setShowIcon(true);
else
setShowIcon(false);
};
{
showIcon ?
<div className="float-item" onClick={
scrollToTop}>
<img className="img-one" src={
require('../../../assets/image/icon-top.png')}/>
<img className="img-two" src={
require('../../../assets/image/icon-top-w.png')}/>
</div>
: ""
}