我有一个简单的点击功能,当点击一个按钮时,用户无法滚动。一切正常。该按钮用作切换,并且在切换的“其他”部分,即当用户再次单击时,我想删除阻止用户使用removeEventListener();
方法滚动的事件监听器。我在这个方法中调用的函数不起作用了吗?
我似乎无法解决问题所在?
codepen:https://codepen.io/emilychews/pen/MrBvzP
JS
var button = document.getElementById("button");
// function to be called and removed when button is clicked
function noscroll() {
window.scrollTo(0, 0);
}
// TOGGLE EVENT LISTENER
var scrollToggle = false;
function toggleEventListener() {
if (scrollToggle === false) {
window.addEventListener("scroll", function(){
noscroll();
}, false);
scrollToggle = true;
} else {
window.removeEventListener("scroll", function(){
noscroll();
}, false);
scrollToggle = false;
}
}
button.addEventListener("click", function() {
toggleEventListener();
}, false)
body {margin: 0; padding: 0; height: 150vh;}
#button {font-family: arial;
margin: 10px 0 0 30px;
width: 100px;
height: 50px;
background: red;
display: flex;
justify-content: center;
align-items: center;
color: white;
cursor: pointer;
}
<div id="button">Click Me</div>
答案 0 :(得分:5)
我不相信你可以remove an anonymous event handler。您需要对其进行命名,以便它知道哪个侦听器匹配。我们可以重用您的noscroll
函数作为我们的命名处理程序。
尝试运行代码段,您会发现它有预期的结果。
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener
var button = document.getElementById("button");
// function to be called and removed when button is clicked
function noscroll() {
window.scrollTo(0, 0);
}
// TOGGLE EVENT LISTENER
var scrollToggle = false;
function toggleEventListener() {
if (scrollToggle === false) {
window.addEventListener("scroll", noscroll, false);
scrollToggle = true;
} else {
window.removeEventListener("scroll", noscroll, false);
scrollToggle = false;
}
}
button.addEventListener("click", function () {
toggleEventListener();
}, false)
&#13;
body {margin: 0; padding: 0; height: 150vh;}
#button {font-family: arial;
margin: 10px 0 0 30px;
width: 100px;
height: 50px;
background: red;
display: flex;
justify-content: center;
align-items: center;
color: white;
cursor: pointer;
}
&#13;
<div id="button">Click Me</div>
&#13;
我们可以通过移动逻辑来检查scrollToggle
到处理程序本身来进一步简化这一过程。无需添加/删除处理程序。 (它可以保持匿名。)
var button = document.getElementById("button");
// TOGGLE EVENT LISTENER
var scrollToggle = false;
window.addEventListener("scroll", () => {
if (scrollToggle) {
window.scrollTo(0, 0)
}
}, false);
function toggleEventListener() {
scrollToggle = !scrollToggle;
}
button.addEventListener("click", function () {
toggleEventListener();
}, false)
&#13;
body {margin: 0; padding: 0; height: 150vh;}
#button {font-family: arial;
margin: 10px 0 0 30px;
width: 100px;
height: 50px;
background: red;
display: flex;
justify-content: center;
align-items: center;
color: white;
cursor: pointer;
}
&#13;
<div id="button">Click Me</div>
&#13;
答案 1 :(得分:0)
这种方法怎么样?
window.removeEventListener("scroll", noscroll);