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 でも変更しました)。また、クラス センターを使用してすべての要素に対して関数を繰り返すコードを少し挿入しました。問題は、それが機能せず、どこが間違っているのかわかりません..
何か案は?