jquery - 当项目变得可见时防止鼠标悬停行为
我有一个按钮“添加到购物车”,单击该按钮会发送 ajax 请求。请求成功返回后,该按钮将替换为“在您的购物车中”。 “在您的购物车中”有一个鼠标悬停状态:“从购物车中删除”。
设计要求是,仅当用户将鼠标物理移动到“在您的购物车”上时,才会出现“从购物车中删除”。如果他们只是单击“添加到购物车”而不移动鼠标,则在 ajax 调用完成后,按钮应该显示“在您的购物车中”,即使鼠标仍在该元素上也是如此。
简单的鼠标悬停事件侦听器不起作用,因为它会在元素变得可见时触发。我正在考虑对包装元素的鼠标悬停和鼠标移出进行计数,以确定鼠标悬停事件是否是“真实的”,或者只是元素变得可见的结果,但这真的很难看。对我来说还有其他想法吗?
I have a button, "Add to Cart" which sends an ajax request when clicked. After the request returns successfully, the the button is replaced by "In Your Cart". "In Your Cart" has a mouseover state: "Remove From Cart".
The design requirement is that "Remove From Cart" only appear when the user physically moves the mouse over "In Your Cart". If they simply click "Add to Cart" and don't move the mouse, the button should say "In Your Cart" after the ajax call completes, even if the mouse is still over the element.
A simple mouseover event listener doesn't work, because it triggers when the element becomes visible. I'm considering counting mouseovers and mouseouts of a wrapper element, in order to determine if the mouseover event is "real", or just the result of the element becoming visible, but that's really ugly. Any other ideas for me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以执行以下操作(根据您的 AJAX 调用进行适当编辑):
HTML:
Javascript:
jsFiddle
< strong>更新
根据下面OP的评论,我更新了HTML和Javascript,如下所示:
Javascript:
这里的区别是:
add-cart
按钮被禁用,并且然后隐藏。mouseover
和mouseout
已替换为mouseenter
和mouseleave
。span
包装器绑定在一起,以便可以更好地跟踪用户鼠标行为,因为span
永远不会隐藏自身。更新了 jsFiddle
You could do something like this (edit as appropriate for your AJAX call):
HTML:
Javascript:
jsFiddle
UPDATE
Based on OP's comment below, I've update the HTML and Javascript as follows:
Javascript:
The differences here are:
add-cart
button is disabled while AJAX is simulated and then hidden.mouseover
andmouseout
have been replaced withmouseenter
andmouseleave
.span
wrapper so that the user mouse behavior can be tracked better since thespan
never hides itself.Updated jsFiddle
您可以使用 jQuery 的 event.preventDefault() 来阻止事件触发;
我会这样写:
这将阻止它执行它应该执行的操作,直到您稍后手动触发它,或者在 event.preventDefault(); 之后添加代码。让它做你想做的事。
You can prevent an event from firing by using jQuery's event.preventDefault();
I would write it this way:
This will stop it from doing what it is supposed to do until you manually fire it later, or add code after the event.preventDefault(); to make it do what you want.
使用 jquery,mouseenter 和 mouseleave 仅在您进入或离开时触发...因此,在 ajax 成功时为图像使用静态大小的包装器
,将图像淡入您想要的
mouseenter,检查单击“添加到购物车”时设置的标志,如果设置了,您就知道用户单击了顺序,移动了鼠标,然后移回了..
using jquery, mouseenter and mouseleave only fire when you enter or leave... so use a static sized wrapper for your image
onsuccess of the ajax, fade the image to what you want
mouseenter, check a flag you set when add to cart was clicked, if its set, you know the user clicked order, moved the mouse, then moved back in..