2015-09-08 53 views
1
<div id="box"> 
    <div> 
     <input type="text" class="temp" /> 
     <div class="list"> 
      focus <br /> 
      two <br /> 
      three 
     </div> 
     <div class="info">Test info </div> 
    <div> 
     <input type="text" class="temp" /> 
     <div class="list"> 
      test1 
      two <br /> 
      three 
     </div> 
     <div class="info">Test info </div> 
    </div> 
    <div> 
     <input type="text" class="temp" /> 
     <div class="list"> 
      test2 
      two <br /> 
      three 
     </div> 
     <div class="info">Test info 444</div> 
    </div> 
</div> 

的jsfiddle:http://jsfiddle.net/ykw67nuv/1/顯示和隱藏在所有

我怎麼可以顯示在所有div(位置:絕對)div.desc在這個例子嗎?我想立即在輸入下面輸入div.desc(通過div.info等)。

第二個問題:如果我單擊外部input.temp,如何隱藏div.desc?

+0

jQuery有'.offset()'來獲取和設置元素 – PitaJ

+0

的絕對位置,要回答你的第二個問題,請參考[這個答案](http://stackoverflow.com/a/32445720/4642212)。 – Xufox

回答

0

$('.temp').focus(function(){        // on focus... 
 
    $(this).closest('div').find('.desc').css({    // Get desc 
 
     top: $(this).offset().top + $(this).outerHeight() // set Y pos 
 
    }).show();            // and show it. 
 
}).blur(function(){          // On blur... 
 
    $(".desc").hide();          // hide all. 
 
});
.desc { 
 
    background-color: green; 
 
    display: none; 
 
    position:absolute;         /* add this */ 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="box"> 
 
    <div> 
 
     <input type="text" class="temp" /> 
 
     <div class="info">Test info </div> 
 
     <div class="desc"> 
 
      focus <br /> 
 
      two <br /> 
 
      three 
 
     </div> 
 
    </div> 
 
    <div> 
 
     <input type="text" class="temp" /> 
 
     <div class="info">Test info </div> 
 
     <div class="desc"> 
 
      test1 
 
      two <br /> 
 
      three 
 
     </div> 
 
    </div> 
 
    <div> 
 
     <input type="text" class="temp" /> 
 
     <div class="info">Test info 444</div> 
 
     <div class="desc"> 
 
      test2 
 
      two <br /> 
 
      three 
 
     </div> 
 
    </div> 
 
</div>

0

你可以得到目前主要集中在輸入框的位置和你的.desc元素相應然後定位。不要忘了讓.desc元素的position:absolute

$('.temp').focus(function(){ 
    $(this).parent('div').find('.desc').toggleClass('show').css({ 
    left:$(this).position().left, 
     top:$(this).position().top+$(this).height()+10, 
     width:($(this).width()+10)+'px' 
    }); 
}).blur(function(){ 
    $(this).parent('div').find('.desc').toggleClass('show'); 
}) 

更新小提琴http://jsfiddle.net/ykw67nuv/3/