javascript - Javascript 在不破坏应用程序的情况下创建异步函数
问题描述
我有一个项目,其中有一个溢出的单杠。在开头和结尾有移动溢出位置的按钮。此时,用户必须单击按钮才能移动溢出。
我不想创建当悬停在它们上方时不断移动溢出直到到达终点或用户从按钮上移开鼠标时的按钮。编码
我试图将“oclick”更改为“onmouseover”并使函数异步。然后添加第二个“onmouseout”功能。但我一直在不断循环,网络应用程序中断。
let isHovered = false;
async function scollTopBar(direction) {
var parent = document.getElementById("parent");
isHovered = true;
let amount = 1;
while(isHovered){
if (direction === "left") amount *= -1;
parent.scrollLeft += amount;
setTimeout(() => {}, 100);
}
}
function mouseRemoved() {
isHovered = false;
}
我没有包含上面的代码,以免破坏浏览器。
var parent = document.getElementById("parent")
function scollTopBar(direction) {
var parent = document.getElementById("parent");
let amount = 20;
if (direction === "left") amount *= -1;
parent.scrollLeft += amount;
}
.cotainer {
width: 30rem;
height: 3rem;
display: flex;
background-color: red;
}
p{
margin: 0;
padding: 0;
white-space: nowrap;
}
button {
height: 100%;
}
.parent {
height: 100%;
display: flex;
align-items: center;
overflow: auto;
}
.child {
padding: 0 1rem;
border-right: 1px solid blue;
background-color: green;
display: inline-flex;
}
<div class="cotainer">
<button onclick="scollTopBar('left')">b</button>
<div class="parent" id="parent">
<div class="child">
<p>Hello</p>
<p>Hello</p>
</div>
<div class="child">
<p>Hello World</p>
<p>Hello</p>
</div>
<div class="child">
<p>Hello WorldHelloWorld</p>
<p>Hello</p>
</div>
<div class="child">
<p>World</p>
<p>Hello</p>
</div>
<div class="child">
<p>Hello WorldHello World</p>
<p>Hello</p>
</div>
<div class="child">
<p>Hello</p>
</div>
<div class="child">
<p>HelloWorld</p>
<p>Hello</p>
</div>
<div class="child">
<p>HelloWorld</p>
<p>Hello</p>
</div>
</div>
<button onclick="scollTopBar('right')">n</button>
</div>
解决方案
在 vanilla JS 中,你应该有这样的东西,左右是按钮 --->
let left = document.getElementById("left");
let right = document.getElementById("right");
left.onmouseover = () => {
scrollTopBar(-20);
};
right.onmouseover = () => {
scrollTopBar(20);
};
function scrollTopBar(direction) {
var parent = document.getElementById("parent");
let int = setInterval(() => {
parent.scrollLeft += direction;
}, 100);
left.onmouseout = () => {
clearInterval(int);
};
right.onmouseout = () => {
clearInterval(int);
};
}
推荐阅读
- android - 当 uid 更改时,为用户订阅 Firebase 中的主题
- python - 重新排序多索引 Pandas 数据框
- reactjs - 访问 React 组件底层 DOM 树
- javascript - 使用 fetch.catch 时在控制台中出现错误
- java - 过滤后的android ListView重复项
- .net-core - 在 dotnet 2.x 版本中使用 include 和 orderby 会引发 Null 异常
- python - Pyspark - 涉及最后一天的“递归”函数
- unity3d - 如果启用了 Internet,Unity 不会加载项目
- java - 隐藏工厂实现
- linux - 如何将物理地址映射到适合 get_user_pages_fast() 的用户空间虚拟地址?