gpt4 book ai didi

Javascript 函数不会重复自身

转载 作者:行者123 更新时间:2023-11-28 09:20:55 24 4
gpt4 key购买 nike

我正在尝试在 Javascript 的帮助下垂直对齐网站上的每个 .class。到目前为止我得到了这个:

<script type="text/javascript">
function setContent() {
var windowHeight = 67;
if (windowHeight > 0) {
var contentElement = document.getElementById('center');
var contentHeight = contentElement.offsetHeight;
if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
}
}
}
window.onload = function() {
setContent();
}
</script>

这有效,但仅适用于具有 ID 中心的第一个元素。由于我有 6 个元素需要更改,因此我将代码更改为:

<script type="text/javascript">
function setContent() {
var windowHeight = 67;
if (windowHeight > 0) {
var contentElement = document.getElementsByClassName('center');
var contentHeight = contentElement.offsetHeight;
if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
}
}
}
$('.center').each(function(){
$(this).setContent();
});
</script>

我更改了 document.getElementById('center');到 document.getElementsByClassName('center');所以它需要所有的类(是的,我也在 html 中更改了它)。我还插入了一些代码,这些代码应该为类中心的每个元素重复该功能。问题是,它不起作用,我不知道哪里出了问题..

有什么想法吗?

最佳答案

尝试进行以下更改:

        function setContent() {
var windowHeight = 67;
if (windowHeight > 0) {
var elems = document.getElementsByClassName('center');
for(var i in elems) {
var contentElement = elems[i];
var contentHeight = contentElement.offsetHeight;
if (windowHeight - contentHeight > 0) {
contentElement.style.position = 'relative';
contentElement.style.top = ((windowHeight / 2) - (contentHeight / 2)) + 'px';
}
}
}
}
window.onload = function() {
setContent();
}

关于Javascript 函数不会重复自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14980842/

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