2016-12-31 57 views
0

我有3個要素相同類別:.tip-container如何僅在一個元素上觸發事件?

而且我想在mouseenter,但只有在懸停的元素觸發事件。

我有這個網站:

<div class="personal_info_form"> 
    <div class="form-group">   
    <span class="information-sign"></span> 
    <div class="tip-container hidden"> 
     <div class="tip">Phone: 7777777777</div> 
    </div>  
    </div> 
    <div class="form-group">   
    <span class="information-sign"></span> 
    <div class="tip-container hidden"> 
     <div class="tip">Email: [email protected]</div> 
    </div>  
    </div> 
    <div class="form-group">   
    <span class="information-sign"></span> 
    <div class="tip-container hidden"> 
     <div class="tip">Address: this is the address</div> 
    </div>  
    </div> 
</div> 

我有這個js:

Drupal.behaviors.personalInfo = (function(){ 
    var _attach = function(context){ 
      $('.personal_info_form', context) 
      //.once() 
      .each(function(i, section){ 
       new PersonalInfo($(section)); 
      }); 
    }; 

    return { 
      attach: _attach 
    }; 
})(); 

function PersonalInfo($el){ 
    this.$el = $el; 
    this.infoSign = this.$el.find('.information-sign'); 
    this.tipContainer = this.$el.find('.tip-container'); 
    this.toggleInfoSign(); 
    return this; 
} 

PersonalInfo.prototype.toggleInfoSign = function(){ 
    var THIS = this; 
    $(THIS.infoSign).on({ 
     mouseenter: function() { 
      THIS.tipContainer.removeClass('hidden'); 
     }, 
     mouseleave: function() { 
      THIS.tipContainer.addClass('hidden'); 
     } 
    }); 

    return THIS; 
}; 

尖端容器默認是隱藏的,所以當你懸停span與類information-signtip-containerdiv應該在鼠標離開時顯示或隱藏。 現在,當您將鼠標懸停在任何.information-signspan s上時,其他隱藏元素將顯示出來。

我該怎麼辦?

回答

1

我認爲CSS會是一個更好的選擇 - demo

這應該給你所需要的一個基本思想:

.tip-container.hidden { 
    display: none; 
} 
span.information-sign { 
    position: relative; 
} 
span.information-sign:hover + .tip-container.hidden { 
    display: block; 
    position: absolute; 
    left: 50px; 
    border: 1px solid #000; 
    width: 200px; 
    height: 50px; 
} 
1

的問題是,你不是在每一節調用new PersonalInfo ,你只是在整個表單上調用它。所以this.$el.find('.tip-container')返回所有.tip-container DIV,而不僅僅是一個。

Drupal.behaviors.personalInfo = (function(){ 
    var _attach = function(context){ 
      $('.personal_info_form .form-group', context) 
      //.once() 
      .each(function(i, section){ 
       new PersonalInfo($(section)); 
      }); 
    }; 

    return { 
      attach: _attach 
    }; 
})(); 
相關問題