【问题标题】:jQuery check offsetjQuery 检查偏移量
【发布时间】:2010-04-19 12:09:28
【问题描述】:

HTML:

<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 块提供一个类:

  • 如果从右侧(浏览器窗口的角)偏移小于小于 150 像素,则 .over 块添加类“right”
  • 如果从右侧偏移大于超过 150 像素 - .over 块添加类“left”

我们该怎么做?

【问题讨论】:

    标签: jquery toggle offset


    【解决方案1】:

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

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

    很明显,您从.offset() 获得了左侧偏移量。您需要创建条件的正确偏移量应计算为:

    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'); }
     });
    });
    

    【讨论】:

    • 能给个完整的功能吗?使用“if”“else”等(如果从右侧偏移小于 150px,则为 .over 块添加类“right”|| 如果从右侧偏移超过 150px - 为 .over 块添加类“left”)
    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 2016-03-05
    • 2020-08-16
    • 2011-12-21
    • 1970-01-01
    相关资源
    最近更新 更多