2010-11-30 52 views
0

我试图在我正在查看的图像顶部添加图形指示器。我基本上会把包含更高Z-index的DIV对象放在我看到的图像的顶部。主图像可以是任何尺寸。jquery - 在屏幕上查找图像的中心部分

因此,当我单击“添加指示器”时,指示器图形总是会弹出到主图像容器顶部的视图中(而不是在它之外),并可由我查看?

另一种情况是,如果图像非常高(如3000像素高度,则需要滚动)。所以我可能会查看图像的底部。

欢迎任何建议!

回答

1

我希望这一点的解决方案将帮助你。您可以在这里看到它的动作: http://jsfiddle.net/neopreneur/ZQqbQ/

在第二个示例中,滚动图像并单击按钮以查看指示符重新居中。

-css-

.fancy-img{ 
    display:inline-block; 
    position: relative; 
    max-height:400px; 
    max-width: 300px; 
    overflow: auto; 
} 

.indicator{ 
    width: 50px; 
    height: 50px; 
    border: 2px solid green; 
    position: absolute; 
} 

-html-

<div class="fancy-img"> 
    <img id="img1" src="http://upload.wikimedia.org/wikipedia/en/7/72/Example-serious.jpg" alt="" /> 
</div> 

<div class="fancy-img"> 
    <img id="img2" src="http://upload.wikimedia.org/wikipedia/commons/thumb/8/84/Example.svg/600px-Example.svg.png" alt="" /> 
</div> 

-js-

$(document).ready(function(){ 
    // add indicator functionality for each img 
    $('.fancy-img').each(function(){ 
     // button to toggle indicator 
     $(this).after('<button class="indicator-btn" data-imageid="' + $(this).find('img').attr('id') + '" type="button">Adjust Indicator</button>'); 
    });  

    // handle button click 
    $('button.indicator-btn').click(function(){ 
     var imgId = $(this).data('imageid'); 

     // insert indicator 
     $('#' + imgId).before('<div class="indicator" />'); 

     // center indicator (also adjust for offset) 
     var containerWidth = $('#' + imgId).parents('.fancy-img:first').width(); 
     var containerHeight = $('#' + imgId).parents('.fancy-img:first').height(); 
     var indicatorWidth = $('.indicator:first').width(); 
     var indicatorHeight = $('.indicator:first').height(); 
     var newIndicator = $('#' + imgId).parents('.fancy-img:first').find('.indicator'); 

     $(newIndicator).css({ 
      left: containerWidth/2 - indicatorWidth /2 + $('#' + imgId).parents('.fancy-img:first').scrollLeft(), 
      top: containerHeight/2 - indicatorHeight/2 + $('#' + imgId).parents('.fancy-img:first').scrollTop() 
     }); 
    }); 
}); 

让我知道,如果这有助于。干杯!

+0

精美的作品!非常感谢! – 2010-11-30 02:23:47

1

那么你用css绝对定位和zindex来获得ontop?并用百分比来定位它在中心

编辑: 如果你表现出一定的HTML我可能是有点更有益

例如

<div style="position:relative;"> 
<div style="position:absolute; margin-left:50%; margin-top:50%;"></div> 
<img src="image.jpg"/> 
</div> 
+0

谢谢!很聪明! – 2011-11-02 01:48:59

1

这应该是很容易做到的

1)获取图像的偏移想要

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

它为您提供顶部和左侧属性,然后使用该位置您的div

使div的绝对位置和给出更好的z-索引。

关于滚动问题的使用,文档高度和计算剩余空间的基础上,你可以定位你的呼叫。

有很多的插件已经速效像提示,拨打出局等,在谷歌搜索也