使用jQuery动态定位元素

ila*_*ann 1 html javascript css jquery

我正在使用菜单栏,每个菜单栏项都是一个图像,当用户将鼠标放在菜单项上时,将显示带子菜单的div.

我想直接把div的,适当的图像项(没有空间,和DIV将徘徊所有元素以上),与右侧对齐,这意味着div的右上角应在图像的右下角.

因为我不能也不想硬编码div的位置,我想动态地做.

现在我有这个:

$('img').each(function(){                     
   jQuery(this).mouseenter(function(){
     var menuItem = $('#' + this.id + '_menu'); //get the needed div 
     var imgRight = this.offset() + this.width();


   });
 });
Run Code Online (Sandbox Code Playgroud)

Sar*_*raz 7

offset()方法具有topleft性能,你需要使用它们,例如:

var imgRight = this.offset().left + this.width();
var imgTop = this.offset().top + this.height();
Run Code Online (Sandbox Code Playgroud)

之后,您必须将absolute定位给DIV以将它们放置在图像下方:

menuItem.css({
  position:'absolute',
  top: imgTop,
  left: imgLeft,
  zIndex:5000
});
Run Code Online (Sandbox Code Playgroud)

所以你的代码变成:

$('img').each(function(){                     
   jQuery(this).mouseenter(function(){

   var menuItem = $('#' + this.id + '_menu'); //get the needed div 
   var imgRight = this.offset().left + this.width();
   var imgTop = this.offset().top + this.height();

     menuItem.css({
       position:'absolute',
       top: imgTop,
       left: imgLeft,
       zIndex:5000
     });

     // now show the corresponding div
     menuItem.show('slow');

   });
});
Run Code Online (Sandbox Code Playgroud)

更多信息:

http://api.jquery.com/offset/