我正在为一个学校项目的网站工作,我在使用javascript时遇到了麻烦。我不是js的粉丝,因为我总是遇到问题,我似乎永远无法让他们在没有帮助的情况下弄明白,但这是该项目的要求之一。我试图让页面中的标题从页面左侧移入,并在页面加载时进入中心。这是我的代码:
JS:
function animate() {
function movetext() {
obj = document.getElementById('spacer');
obj.style.position ='relative';
obj.style.left = '-100px'; //still needs to be adjusted
}
function moveright() {
obj.style.alignContent="center";
obj.style.animation="move 2s";
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lockport, NY - Activities</title>
<link rel="stylesheet" href="project.css">
<link href='https://fonts.googleapis.com/css?family=Oleo+Script+Swash+Caps' rel='stylesheet' type='text/css'>
</head>
<body onload="animate();">
<!-- Background -->
<div class="background">
<!-- Navigation -->
<?php
include 'includes/nav.php';
?>
<!-- Title -->
<div id="spacer"><p span class="titles">Activities...</p></div>
<div id="wrapper">
<div id="main">
//code removed for readability
</div>
<!-- Footer -->
<?php
include 'includes/footer.php';
?>
</div>
</div>
</body>
<script src="project1.js"></script>
</html>
我知道在编码时我不是最好的,我知道它可能是一个简单的修复,但我找不到它。感谢帮助。
答案 0 :(得分:1)
您可以使用CSS动画轻松完成此操作:
setTimeout(function() {
document.getElementById('spacer').classList.add('show');
}, 100);
&#13;
#spacer {
position: absolute;
right: 100%;
transition: right 3s;
}
#spacer.show {
right: 50%;
}
&#13;
<div id="spacer">
<p class="titles">
Hello
</p>
</div>
&#13;
答案 1 :(得分:0)
更优雅的解决方案是使用两个类(例如.centerpos,.title),并为类分配样式,以便通过js对文本进行居中。
所以它看起来像那样:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lockport, NY - Activities</title>
<link href='https://fonts.googleapis.com/css?family=Oleo+Script+Swash+Caps' rel='stylesheet' type='text/css'>
</head>
<style>
.title {
position: absolute;
left: -100px;
transition: left 2s;
}
.title.centerpos {
left: 50%;
transform: translate(-50%, 0);
}
</style>
<body onload="document.querySelector('.title').classList.add('centerpos');">
<div class="background">
<div id="spacer"><p span class="titles title">Activities...</p></div>
<div id="wrapper">
<div id="main">
//code removed for readability
</div>
</div>
</div>
</body>
</html>