Get scroll height and set as top to an absolute positioned element

I need to show one image in light box.

I had given postion:fixed earlier. But when the image height is bigger than the screen height, it leads to problem.

Problem is:

Now I need to use absoulte concept. But problem here is, if i give a static "top" value in CSS, lightbox image will be shown at the top of the page, when a user clicks a link which is at bottom of the page.

TO DO:

I need to set scrolled height of the page as top: value of the lightbox imageimage . I tried scrollTop(). But didn't get.

How to do that?

Can you guys please tell me?

Edit: Here is my concept: http://jsfiddle.net/velmurugansp/F7z4f/1/

<div stle="position:relative">
<div style="height:1000px">
Top Contents
</div>
<img src="http://ftape.com/model/wp-content/uploads/2011/02/Caroline-Corinth-Models1-The-Model-Wall_4.jpg" width="630" height="630" style="position:absolute; top:0; left:-50%; margin-left:315px;display:block" id="img" />
</div>

<script>
scrollHeight=document.scrollTop();
$("#img").css("top",scrollHeight);
</script>

I need to give top:1000px; to "#img". Cos the height of previous element's height is 1000px;


To set a top position for the image can be used something like this:

jQuery(document).ready(function() {
    $(window).scroll(function() {
        var scrollHeight = $(window).scrollTop();
        var img = $('#img');
        if (scrollHeight < $(document).height()-img.height()-20) {
            img.css("top", scrollHeight);
        }
    });
});

jsfiddle


Yoy需要获得body或html元素的scrollTop(),而不是其他元素。


Can you not change the height of your image using CSS? It might prevent the necessity for all the jQuery.

链接地址: http://www.djcxy.com/p/72056.html

上一篇: 使用jQuery Scroll实现CSS动画

下一篇: 获取滚动高度并设置为绝对定位元素的顶部