开发者

Trying to make a div appear in the centre of a scrollable page - bug in my code?

Just as a preface to make sure I am clear, I don't want the div to appear dead centre in the middle of the page, I want it in the middle of the viewable window. So if you imagine a long page and the user has scrolled down to near the bottom and clicks the button the div will appear in the centre of the screen near the bottom of the page.

here is my code, which doesn't work in chrome:

                function centerdiv() {
var scrolledX, scrolledY;

scrolledX = document.body.scrollLeft;
scrolledY = document.body.scrolltop;

var centerX, centerY;
centerX = document.body.clientWidth;
centerY = document.body.clientHeight;

var leftoffset = scrolledX + (centerX - 100) / 2;
var topoffset = scrolledY + (centerY - 100) / 2;

 $('.current div[name="popup"]').css({'top' : topoffset + 'px', 'left':
 leftoffset + 'px'});} 


            $(function() {
        $("html").ajaxStart(function() {
           centerdiv();
            $(".current div[name=popup]").show();
        });
        $("html").ajaxComplete(function() {
            $(".current div[name=popup]").hide();
       开发者_Python百科 });
    });

Note, this is for an iphone mobile website and the ajaxstart function attaching to the html is crucial as it doesn't work on the iphone any other way on my website.


You forget to set position to absolute, or fixed

$('.current div[name="popup"]').css({'top' : topoffset + 'px', 'left': leftoffset + 'px', 'position':'absolute' });}


Here is my solution that works fine:

    var winH = $(window).height();
    var winW = $(window).width();
    $(this).css('top', winH/2 - $(this).height()/2);
    $(this).css('left', winW/2 - $(this).width()/2);
    $(this).show();

$(this) must refer to the DIV element you want to show in the center.


wh = $(window).height();
dh = $("#div").height();
$("#div").css("top",(wh - dh)/ 2 + $(window).scrollTop() + 'px');

Edit: Not the same for width, it's actually:

ww = $(width).width();
dw = $("#div").width();
$("#div").css("left",(ww - dw)/ 2 + 'px');

But it really depends if you have a fixed viewport or not, there are many ways to center it...

Good Luck!


If you don't have horizontal scrolling you can do it partially with straight CSS div{ left: 50%; margin-left: -[box_width / 2]px; }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜