将鼠标悬停在prepend()函数中

时间:2016-11-06 16:41:41

标签: javascript jquery

HTML:

<div class="Wrap">
    <div class="container">
        <div class="count">My Counter</div>
        <div class="background"></div>
        <div class="hover"></div> 
    </div>
</div>
<button class="AddDiv">AddDiv</button>

jQuery的:

$('.AddDiv').on('click', function(){
    $('.Wrap').prepend($('<div class="container"><div class="background"></div><div class="hover"></div></div>')); 
});

$(".background").on("mouseover", function () {
    $(".hover").fadeIn(500);
});

$(".hover").on("mouseout", function () {
    $(".hover").fadeOut(200);
});

https://jsfiddle.net/mpd075s8/5/

您好,我有悬停问题,看看jsfiddle并点击按钮AddDiv,当悬停在绿色广场上时,所有的div都是div,但我希望每个div都会分开悬停。并且悬停在新的div中不起作用

2 个答案:

答案 0 :(得分:2)

两件事

  1. 您需要将delegated event用于动态元素

  2. 使用this作为当前元素的参考。

  3. 尝试以下。

    $('.AddDiv').on('click', function() {
        $('.Wrap').prepend($('<div class="container"><div class="background"></div><div class="hover"></div></div>'));
    });
    
    $(".Wrap").on("mouseover", ".background", function () {
        $(this).next(".hover").fadeIn(500);
    });
    
    $(".Wrap").on("mouseout", ".hover", function () {
        $(this).fadeOut(200);
    });
    .Wrap {
      width: 650px;
      height: 800px;
    }
    
    .container {
      position: relative;
      top: 5px;
      left: 5px;
      width: 200px;
      height: 200px;
      background-color: red;
      float: left;
      margin-left: 5px;
      margin-top: 5px;
    }
    
    .AddDiv {
      position: absolute;
      top: 0px;
    }
    
    .background {
      width: 20px;
      height: 20px;
      background-color: green;
      position: absolute;
      left: 170px;
      top: 10px;
    }
    
    .hover {
      width: 200px;
      height: 200px;
      background-color: rgba(255, 255, 255, 0.8);
      position: absolute;
      z-index: 1001;
      display: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="Wrap">
      <div class="container">
        <div class="background">
        </div>
        <div class="hover">
        </div>
      </div>
    </div>
    <button class=AddDiv>AddDiv</button>

答案 1 :(得分:1)

您可以使用$(this) jquery函数

$("body").on("mouseover",".background", function () {
    $(this).siblings('.hover').fadeIn(500);
});
$("body").on("mouseout",".hover", function () {
    $(this).fadeOut(200);
});

https://jsfiddle.net/mpd075s8/7/