中心对象与可变宽度使用jQuery [英] center object with variable width using jQuery

查看:154
本文介绍了中心对象与可变宽度使用jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要根据浏览器窗口中心宽度变化的对象。通常我使用css,顶部和左侧的位置设置为50%,负边距等于宽度和高度的一半,但显然不会满足这种需要。

Need to center an object whose width changes depending on the browser window. Usually I'd use css with top and left positions set to 50% with a negative margin equal to half the width and height, but obviously that wouldn't accomodate this need.

我认为我的jQuery函数会工作...但没有bueno。我在CSS中缺少一些东西?

I thought my jQuery function would work... but no bueno. am i missing something in CSS?

谢谢!

http://jsfiddle.net/danielredwood/EbkLg/2/

这里是CSS

#t {
        width:25%;
        height:25%; 
        background:red;
    }

JavaScript

JavaScript

$(window).resize(function(){
     resizenow();
});
function resizenow() {
    var browserwidth = $(window).width();
    var browserheight = $(window).height();
    $('#t').css('left', (browserwidth - $(this).width())/2).css('top', (browserheight - $(this).height())/2);
});


推荐答案

在JSFiddle中, c $ c> $(this).width():

In your JSFiddle that you linked to you use $(this).width():

$('#t').css('left', ((browserwidth - $(this).width())/2))
.css('top', ((browserheight - $(this).height())/2));

但是当调用resizenow()函数时, this == window 。如果你替换 $(this) $(#t)它工作正常,因为JSFiddle显示: http://jsfiddle.net/jackfranklin/F2tR3/1/

But when the function resizenow() is called, this == window. If you replace $(this) with $("#t") it works fine, as this JSFiddle shows: http://jsfiddle.net/jackfranklin/F2tR3/1/

在jQuery的 css()函数中, this 的值不是设置为您要更改的样式的元素,因此您的原始代码无法正常工作。

Within the css() function of jQuery, the value of this is not set to the element whose style(s) you are changing, hence why your original code didn't work.

这篇关于中心对象与可变宽度使用jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆