gpt4 book ai didi

jquery - 应用以下格式,除非视口(viewport)小于容器 div - Jquery

转载 作者:行者123 更新时间:2023-12-01 04:54:56 25 4
gpt4 key购买 nike

我正在尝试在 Jquery 中创建以下内容,我想做的是仅当视口(viewport)比 .container div 大时才将格式应用于 div。我写了以下内容,但我不确定我是否正确地完成了它,因为我的 Jquery 不是那么好。

    $(document).ready(function(){
$(window).width(); // returns width of browser viewport
$(document).width(); // returns width of HTML document

$(window).height(); // returns heightof browser viewport
$(document).height(); // returns height of HTML document

var width = $(window).width(); // the window width
var height = $(window).height(); // the window height
var containerwidth = $('.container').outerWidth(); // the container div width
var containerheight = $('.container').outerHeight(); // the container div height

if ((width >= containerwidth) && (height>=containerheight)){ //if the width and height of the window is bigger than the container run this function
$(document).ready(function(){
$(window).resize(function(){
$('.container').css({
position:'absolute',
left: ($(window).width()
- $('.container').outerWidth())/2,
top: ($(window).height()
- $('.container').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
});
}
});


EDIT >>

...................................................... ......

我在这里创建了一个 js fiddle ,它现在似乎可以工作。

http://jsfiddle.net/QgyPN/

最佳答案

测试窗口尺寸和容器尺寸的方式很好。

但是,您对待事件的说法存在问题。你有

$(document).ready(function() {
//...
});

两次这是没有意义的(顺便说一句,你在 fiddle 中修复了它,这可能就是它起作用的原因)。

据我了解,您正在尝试:1. 当页面加载时,如果窗口足够大,应用一定的CSS。2. 在后续页面调整大小时,执行相同的操作

所以我建议您隔离应用 CSS 的代码。这样您就可以多次使用它:

var positionContent = function () {
var width = $(window).width(); // the window width
var height = $(window).height(); // the window height
var containerwidth = $('.container').outerWidth(); // the container div width
var containerheight = $('.container').outerHeight(); // the container div height

if ((width >= containerwidth) && (height>=containerheight)){
$('.container').css({position:'absolute',
left: ($(window).width() - $('.container').outerWidth())/2,
top: ($(window).height() - $('.container').outerHeight())/2 });
}
};

然后在需要时使用该函数:

//Call it when the window first loads
$(document).ready(positionContent);

//Call it whenever the window resizes.
$(window).bind('resize', positionContent);

关于jquery - 应用以下格式,除非视口(viewport)小于容器 div - Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15026623/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com