2010-04-19 60 views
2

HTML:jQuery的检查偏移

<ul class="clients"> 
<li> 
    <div class="over left">Description</div> 
    <div class="inner">Image</div> 
</li> 
</ul> 

CSS:

.clients { margin-right: -20px; } 
.clients li { 
    float: left; 
    width: 128px; 
    height: 120px; 
    margin: 0 20px 20px 0; 
    border: 1px solid #c2c2c2; 
} 
    .clients .over { 
    display: none; 
    position: absolute; 
    width: 250px; 
    font-size: 11px; 
    line-height: 16px; 
    background: #ecf5fb; 
    margin: 3px 0 0 3px; 
    padding: 18px; 
    z-index: 25; 
    } 
    .clients .right { margin: 3px 0 0 -161px; } 
    .clients .inner { width: 128px; height: 120px; overflow: hidden; } 

因此,我们有浮广场,在每一个弹出框,其中有绝对位置的列表。

JS:

jQuery(function($) { 
$(".clients li").bind('mouseover mouseout',function(){$(this).find("div.over").toggle()}); 
}); 

如果过度 - 显示,否则 - 隐藏。相当确定的,但它必须是更先进的,我们应该抓住的偏移,并给予类.over块:

  • 如果从右侧偏移(浏览器窗口的角落)比为150px,然后.over块添加类“右”
  • 如果从右边偏移更多大于150px - .over块添加类“左”

我们该怎么做?

回答

2

.offset()返回类似{ left: 200, top: 300 }

$(window).width()对象返回窗口宽度

显然你从左边.offset() streight偏移。右偏移你需要与应计算条件:

offsetRight=$(window).width()-$(this).width()-$(this).offset().left; 

一起:

jQuery(function($) { 
$(".clients li").bind('mouseover mouseout',function(){ 
    $over=$("div.over",this); 
    $over.toggle(); 
    //didn't get if it's the li's offset you need or the actual .over, replace $(this) with $over in next lines if you need that 
    offset=$(this).offset(); 
    offsetRight=$(window).width()-$(this).width()-offset.left; 
    if (offsetRight<150){ $over.removeClass('left').addClass('right'); } 
    else { $over.removeClass('right').addClass('left'); } 
}); 
}); 
+0

你可以给一个全功能?使用“if”“else”等(如果右侧偏移量小于150px,则为.over块添加“right”类|| 如果右侧偏移量超过150px - 为.over块添加class“left” ) – Happy 2010-04-19 13:13:59

+0

哇,完美!上帝祝福你。 – Happy 2010-04-19 14:57:44