在页面加载时使用JavaScript在父容器中垂直居中子div是不是设置位置?

编程入门 行业动态 更新时间:2024-10-20 03:35:54
本文介绍了在页面加载时使用JavaScript在父容器中垂直居中子div是不是设置位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用JavaScript将一个子div垂直居中于一个流体容器中。我基本上通过计算父容器的高度和子div的高度来实现这一点。然后我绝对根据高度在父div的中心定位子div。我遇到的问题是,当页面加载时,它不会设置子div的位置。我创建了一个函数,并在调整窗口大小时调用它,以便在视口更改时动态重新计算。如何在页面加载时初始设置此位置?

I am using JavaScript to vertically center a child div within a fluid container. I essentially accomplish this by calculating the height of the parent container and the height of the child div. I then absolutely positon the child div in the center of the parent div based on the height. The issue I am experiencing is that when the page loads, it does not set the position of the child div. I created a function out of this and call it when the window is resized so that when the viewport changes it recalculates dynamically. How would I go about initially setting this position on page load?

<div class="lead"> <div class="message"></div> </div> var homepageLead = function () { var lead = $('.lead'), message = $('.message'), lead_height = lead.height(), message_height = message.height(), lead_center = .5 * lead_height, message_center = .5 * message_height, center = (lead_center - message_center); message.css('bottom',center); } homepageLead(); $(window).resize(function () { homepageLead(); });

推荐答案

试试这个小提琴: jsfiddle/nRRn6/ 使用了css:

Try this fiddle: jsfiddle/nRRn6/ used css:

html, body { height:100%; } .lead { width:100%; height:100%; background:red; position:relative; } .message { width:120px; height:200px; background:yellow; position:absolute; /* <---required*/ left:0; /* <---required*/ bottom:0; /* <---required*/ }

使用的html:

used html:

<div class="lead"> <div class="message"></div> </div>

使用jQuery:

used jQuery:

var homepageLead = function () { var lead = $('.lead'), message = $('.message'), lead_height = lead.height(), message_height = message.height(), lead_center = .5 * lead_height, message_center = .5 * message_height, center = (lead_center - message_center); return message.css('bottom', center); }; $(function () { $(window).resize(function () { homepageLead(); }).resize(); });

更多推荐

在页面加载时使用JavaScript在父容器中垂直居中子div是不是设置位置?

本文发布于:2023-10-08 01:34:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471128.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:容器   加载   位置   页面   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!