有一种方法可以仅使用 jQuery 将 <div> 元素居中到页面中间。
下面的代码片段显示了创建一个函数的方法,我们可以将其添加到脚本中以将 <div> 元素居中:
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script> <style> div.box { width: 400px; height: 300px; border: 2px solid green; position: relative; top: 10px; left: 10px; } div.myclass { width: 50px; height: 50px; color: white; background: green; border-radius: 4px; text-align: center; display: flex; align-items: center; justify-content: center; } </style> </head> <body> <div class="box"> <div class="myclass">Box</div> </div> <script> $(document).ready(function() { jQuery.fn.center = function(parent) { if(parent) { parent = this.parent(); } else { parent = window; } this.css({ "position": "absolute", "top": ((($(parent).height() - this.outerHeight())/2) + $(parent).scrollTop() + "px"), "left": ((($(parent).width() - this.outerWidth())/2) + $(parent).scrollLeft() + "px") }); return this; } $("div.myclass:nth-child(1)").center(true); }); </script> </body> </html>
要使用上述函数,我们应该选择 <div> 元素居中并将其传递给新函数:
$(element).center();
你应该使用 this.outerHeight() 和 this.outerWidth();否则,如果对象有填充或者边框,它最终会偏离中心。
如果 CSS 无法正常工作,jQuery 解决方案可以成为将 <div> 元素居中的完美解决方案。
.outerHeight() 和 .outerWidth() 方法
.outerHeight() 和 .outerWidth() 方法获取匹配元素组中第一个元素的高度和宽度(包括内边距、边框和边距)或者分别设置每个匹配元素的外部高度和宽度。
如果在空元素组上调用两个方法,它们将返回未定义。
日期:2020-06-02 22:16:08 来源:oir作者:oir