如何在 .hover() 中使用油门; jQuery?
Posted
技术标签:
【中文标题】如何在 .hover() 中使用油门; jQuery?【英文标题】:How do I use throttle with .hover(); jQuery? 【发布时间】:2021-12-13 18:12:26 【问题描述】:我正在尝试找到使用 jQuery 来限制悬停功能的最简洁的方法。有很多这样的例子,但它们似乎都没有按预期工作。例如,使用$.throttle
不会出错,但它会完全停止动画的工作。这是我试图限制的代码:
jQuery(document).ready(function($)
var $navTab = $('.nav-tab-parent');
function moveNavTab(e)
TweenLite.to($navTab, 0.3,
css:
left: e.pageX,
top: e.pageY
);
$(window).on('mousemove', moveNavTab);
$(".toggle-bars").hover( // this is the .hover() function I need to throttle.
function()
$(".nav-tab-parent").animate(
opacity: 1
);
$(".nav-tab-parent").delay(10).animate(
width: "36px",
easing: "swing"
);
$(".nav-tab").html("MENU");
$(".nav-tab").delay(350).animate(
opacity: 1
);
, function()
$(".nav-tab").animate(
opacity: 0
);
$(".nav-tab-parent").delay(150).animate(
width: "0",
opacity: 0,
easing: "swing"
);
);
);
我一定在这里遗漏了一些东西,但无法弄清楚。任何帮助实现这一点将不胜感激!
【问题讨论】:
您实际上想要达到什么目的?在动画仍在运行时不启动动画? @t1m0n 将鼠标悬停在页面上的某些链接上时会出现一个动画文本字段,问题是如果用户悬停和取消悬停然后重新悬停足够快,它会破坏动画的循环.因此,对于无缝动画,我需要限制悬停功能,以便动画不能在状态之间滑动 我以前的技巧是在每个动画之前调用.stop()
。这也与 jQuery 文档中的悬停一起解释。所以请在此处阅读文档:stop()
你在使用 GSAP tweenlite 吗?我记得那里有一个动画“!while”功能,但想确认一下。
@coll 是的,它是 GSAP TweenMax 库
【参考方案1】:
更改为完全使用 GSAP 并依赖 .timescale()
参见 documentation — 不知道底层结构,因此需要一些配置,但基础在那里。 GSAP has a crazy deep documentation 但应该对 jquery 对象动画足够熟悉。
var tl = gsap.timeline().timeScale(-1);
tl.fromTo(".nav-tab-parent",
autoAlpha: 0,
duration: 1
,
autoAlpha: 1,
duration: 1
);
$(".toggle-bars").hover(function()
tl.timeScale(1);
, function()
tl.timeScale(-1);
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.8.0/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle-bars">.toggle-bars
<div class="nav-tab-parent">.nav-tab-parent</div>
</div>
【讨论】:
【参考方案2】:我想你正在尝试实现这样的目标。您可以尝试使用.stop()
方法 - 它会停止当前动画,然后您可以运行下一个动画。尝试使用论据来选择最适合您的情况。
let $hover = $('.hover-box'),
$target = $('.animated-box');
function show()
$target.stop(true, true).animate(
opacity: 1,
)
function hide()
$target.stop(true, true).animate(
opacity: 0
)
$hover.hover(show, hide)
.hover-box,
.animated-box
width: 100px;
height: 100px;
border-radius: 8px;
.hover-box
border: 1px solid #ddd;
display: inline-flex;
align-items: center;
justify-content: center;
text-transform: uppercase;
font-family: sans-serif;
cursor: pointer;
margin-bottom: 16px;
.hover-box:hover
background: #ddd;
.animated-box
opacity: 0;
background: gold;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='hover-box'>Hover</div>
<div class='animated-box'></div>
【讨论】:
以上是关于如何在 .hover() 中使用油门; jQuery?的主要内容,如果未能解决你的问题,请参考以下文章