javascript - 平滑滚动条 - 什么执行滚动事件?
问题描述
我在我的页面上实现了平滑滚动条,效果很好,但我还想在滚动内容中添加一些过渡效果。基本上我想在滚动事件上执行此操作,但我不知道平滑滚动条的工作原理以及在滚动事件上执行的对象。我检查了#my-scrollbar 没有这样做:
$("#my-scrollbar").on("scroll", function () {
console.log("scroll"); //not working
});
滚动事件的原因是什么?还是有另一种方法可以在不检查滚动事件的情况下做一些额外的效果?
编辑:我正在粘贴我的代码(我正在使用 React.js)来解释更多。
索引.html
<!DOCTYPE html>
<html>
<head>
<title>Smooth scrollbar with parallax</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="my-scrollbar">
<div id="root"></div>
</div>
</body>
</html>
index.js
import React from "react";
import ReactDOM from "react-dom";
import "./website/App.css";
import App from "./website/App";
import Scrollbar from "smooth-scrollbar";
Scrollbar.init(document.querySelector("#my-scrollbar"));
ReactDOM.render(<App/>, document.getElementById("root"));
应用程序.js
import React, { Fragment, Component } from "react";
import $ from "jquery";
class App extends Component {
componentDidMount() {
$(document).on("scroll", function (e) {
console.log(e);
});
const h1posX = 64;
const h1posY = 64;
$("#section2 h1").css({ transform: `translate(${h1posX}px,${h1posY}px)` });
window.addEventListener("scroll", function () {
const distance = window.scrollY;
console.log(distance);
if (distance <= $("#section1").outerHeight() / 2) document.querySelector(".container2").style.transform = `translateY(${distance * 1.15}px)`;
$("#box2").css({ transfrom: `translateY(${distance}px)` });
$("#section2 h1").css({ transform: `translate(${distance * 0.15}px,${h1posY}px)` });
});
}
render() {
return (
<Fragment>
<main>
<header>
<div className="container2">
<h3>Hello world!</h3>
<p>Scroll to see smooth scrolling</p>
</div>
</header>
<div id="section1">
<h3>Lorem ipsum</h3>
</div>
<div id="section2">
<h1>Dolor sit amet</h1>
</div>
</main>
</Fragment>
);
}
}
export default App;
应用程序.css
header {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
position: relative;
height: 100vh;
color: #eee;
z-index: -1;
text-align: center;
background: linear-gradient(135deg, #0056a7, #165fa3, #477aaa);
animation: fadeIn 1.5s ease-in-out;
}
#section1 {
display: flex;
align-items: center;
justify-content: center;
z-index: 1;
height: 100vh;
font-size: 5rem;
background: transparentize(#47aa79, 0);
}
#section2 {
display: flex;
z-index: 2;
height: 100vh;
font-size: 9rem;
font-weight: bold;
background: #477aaa;
color: #eee;
h1 {
position: absolute;
transition: all 0.1s linear;
}
}
解决方案
您必须将event
句柄作为参数传递给回调函数并使用它。
$("#my-scrollbar").on("scroll", function(event) {
console.log(event);
});
该事件将返回属性对象,您可以使用您需要的任何事件属性,例如:event.type
推荐阅读
- mysql - 插入记录并增加其他记录的值
- php - PHP - 如何获取没有值的 $_GET 参数
- html - 让 MatDatePicker 显示为格式 01/01/2010
- javascript - 如何禁用弹出窗口阻止程序?
- firebase - 使用 Firebase Cloud Functions 为 Live App React Naive 定价的 Stripe Payment
- java - 如何在recyclerview中添加多个过滤器?
- python - Scrapy中的报纸文章刮刀
- axios - 如何在 Axios 中使用“preconnect”和“dns-prefetch”
- c++ - 多层铸造 - C++
- c++ - 是什么导致我的方法中的堆损坏?