我最近更新了我的一个旧的javascript,使其可以与Jquery一起使用。
它执行以下操作:
当用户将鼠标悬停在带有content-fade
类的链接上时,它会导致带有关联id
的内容淡入,然后在设定的时间内淡出,除非用户将鼠标放在内容上。
我需要再次更改脚本,并使其遍历一组id
,即id1、id2、id3...etc。理想地使得仅显示具有个人关联id的内容。我刚刚开始使用JQuery,我不确定如何才是最好的方法。下面是代码,如果有人能给我指出正确的方向,我将不胜感激。
$(document).ready(function() {
var hide = false;
$(".content-fade").hover(function(){
if (hide) clearTimeout(hide);
$("#id").fadeIn();
}, function() {
hide = setTimeout(function() {$("#id").fadeOut("slow");}, 250);
});
$("#id").hover(function(){
if (hide) clearTimeout(hide);
}, function() {
hide = setTimeout(function() {$("#id").fadeOut("slow");}, 250);
});
});
发布于 2011-11-14 06:51:53
如果我正确地理解了您的需求,那么您的思路是正确的。
悬停通过在数据属性悬停(
mouseenter
)中存储悬停选择器来定义目标元素,淡入目标元素。mouseleave
使用mouseenter
上目标元素的悬停来淡出目标,以防止fadeOut挂起。因此,如果用户将光标从链接上移开,然后立即再次返回-在延迟的fadeOut启动之前- fadeOut将被取消,目标元素将保持可见。代码见下文,工作示例见http://jsbin.com/uruzaw/11/。
$(function(){
$('.content-fade').hover(
// fadeIn on mouse
function(event){
var $this = $(this);
var $target = $($this.data('hoverTarget'));
$target.clearQueue().fadeIn(500);
},
// fadeOut on mouseout
function(event){
var $this = $(this);
var $target = $($this.data('hoverTarget'));
$target.delay(500).fadeOut(500);
}
);
});
编辑我想我误解了你的要求。如果您希望在链接和内容本身悬停时防止内容的fadeOut,则以下内容就足够了。它基本上就是您所编写的,但是使用了jQuery动画队列和.delay()
来代替setTimeout()
。请参阅http://jsbin.com/uruzaw/13/
$(function(){
var HOVER_DELAY = 1000;
$('.content-fade').each(function(){
var $this = $(this);
var $target = $($this.data('hoverTarget'));
var fadeTargetElem = function(){
$target.delay(HOVER_DELAY).fadeOut(500);
};
// bind to mouseenter
$this
.mouseenter(function(event){
$target.clearQueue().fadeIn(500);
})
// bind to mouseleave
.mouseleave(function(event){
fadeTargetElem();
});
// bind to mouseenter of target
$target
.mouseenter(function(event){
$target.clearQueue();
})
// bind to mouseleave of target
.mouseleave(function(event){
fadeTargetElem();
});
});
});
发布于 2011-11-14 03:20:10
如果您的is是编号的,那么一个简单的for
循环就可以做到这一点。这个问题,,你的“in”是如何与他们的.content-fade
对应物联系在一起的?这个问题的答案将引导你找到解决方案。
如果每个.content-fade
链接也有一个id
属性集,那么您可以解析它,并在附加mouseenter/mouseleave事件时使用它。
可以这样说:
<a class="content-fade" id="link-1">Link 1</a>
<a class="content-fade" id="link-2">Link 1</a>
然后你可以这样解析它:
var hide = false, id;
$(".content-fade").hover(function() {
if (hide) clearTimeout(hide);
id = this.id.split('-')[1];
$("#id-" + id).fadeIn();
}, function() {
id = this.id.split('-')[1];
hide = setTimeout(function() {$("#id-" + id).fadeOut("slow");}, 250);
});
当然,这意味着必须管理所有不同的超时。
发布于 2011-11-14 03:27:10
要遍历所有这些ids,需要向所有这些元素添加一个类,并在每次迭代时使用each执行操作
https://stackoverflow.com/questions/8113904
复制相似问题