在悬停

时间:2015-06-13 18:28:52

标签: javascript jquery html css ajax

我正在尝试循环悬停效果,使图像跳到网站的四个角(左上角 - >右上角 - >右下角 - >> bottom leftcorner - >然后备份到左上角)

我这样做的方法是添加一个类,hoverleft,right,down,up等,并删除前一个类。我遇到的问题是页面加载后无法识别动态添加的类。我一直在尝试使用.on()函数,但一直遇到困难。不知道为什么,并且很确定我只是错过了一些简单的东西。

这就是我所拥有的,HTML然后JS:在这里小提琴:http://jsfiddle.net/5w0nk6j9/4/

<div class="bodycontainer">
<div id="kim">
    <div id="dance" class="dancingkim">
    <div class="header">
        <h2 class="introheader">Hover original</h2>
    </div>
        <img src="http://placehold.it/240x208" />
</div>
</div>

$('#kim').hover(function(){
    $(".header h2").text("Hover text");
    });
    $('#kim').hover(function(){
    $(".dancingkim").css("cursor", "pointer");
});

$('.dancingkim').hover(function(){
    $(this).addClass("hoverleft");
    $(this).removeClass("dancingkim");
});

$('#kim').on('hover', '.hoverleft', function() {
    $('#dance').addClass("hoverdown");
    $('#dance').removeClass("hoverleft");
});

2 个答案:

答案 0 :(得分:0)

代替悬停,尝试使用鼠标悬停 mouseenter mouseleave

$('#kim').on('mouseover', '.hoverleft', function() {
    $('#dance').addClass("hoverdown");
    $('#dance').removeClass("hoverleft");
});

从JQuery源代码中,hover不包含在触发导致JQuery的事件列表中.on()

答案 1 :(得分:0)

使用.on()引用动态生成的元素,但应在文档正文中实现。 javascript遍历整个文档并将属性添加到它。 所以,而不是使用:

$('#kim').on('hover', '.hoverleft', function() {
$('#dance').addClass("hoverdown");
$('#dance').removeClass("hoverleft");
});

$('#kim').on('hover', '.hoverleft', function() { $('#dance').addClass("hoverdown"); $('#dance').removeClass("hoverleft"); });

试试这个:

$('body').on('mouseover', "#kim", function(){
$(this).next().addClass("hoverdown");
$(this).next().removeClass("hoverleft");
});