我正在尝试使用getEleementById
在不同页面上显示具有两个唯一ID的两个不同元素。一个用于主索引页面,另一个用于项目页面。下面的代码在索引页面上有效,但在项目页面上无效。但是,如果我摆脱了animation1中的调用,那么它将在项目页面上起作用。 document.getElementById
为何即使在两个唯一的ID上被调用也只能使用一次?
function displayTitle(id) {
var elem = document.getElementById(id);
elem.style.display = "block";
}
function animation1() {
displayTitle("main-bnb-logo");
var title1 = new TimelineMax();
title1.staggerFromTo(".title span", 0.5,
{ease: Back.easeOut.config(1.7), opacity: 0, bottom: -80},
{ease: Back.easeOut.config(1.7), opacity: 1, bottom: 0}, 0.05);
}
function animation2() {
displayTitle("project-title-content-wrapper");
var title2 = new TimelineMax();
title2.staggerFromTo(".project-title span", 0.5,
{ease: Back.easeOut.config(1.7), opacity: 0, bottom: -80},
{ease: Back.easeOut.config(1.7), opacity: 1, bottom: 0}, 0.05);
}
$(document).ready(function() {
animation1();
}, 1000);
$(document).ready(function() {
animation2();
}, 1000);
答案 0 :(得分:0)
问题解决了。就像Tapas在评论中说的那样,我需要对displayTitle函数进行空检查:
更新的代码:
function displayTitle(id) {
var elem = document.getElementById(id);
if (elem == null) {
console.log('no id selected');
} else {
elem.style.display = "block";
}
}
function animation1() {
displayTitle("main-bnb-logo");
var title1 = new TimelineMax();
title1.staggerFromTo(".title span", 0.5,
{ease: Back.easeOut.config(1.7), opacity: 0, bottom: -80},
{ease: Back.easeOut.config(1.7), opacity: 1, bottom: 0}, 0.05);
}
function animation2() {
displayTitle("project-title-content-wrapper");
var title2 = new TimelineMax();
title2.staggerFromTo(".project-title span", 0.5,
{ease: Back.easeOut.config(1.7), opacity: 0, bottom: -80},
{ease: Back.easeOut.config(1.7), opacity: 1, bottom: 0}, 0.05);
}
$(document).ready(function() {
animation1();
animation2();
}, 1000);