javascript - 如何在两个不同的 id 上使用 document.getElementById
问题描述
我正在尝试使用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);
解决方案
问题解决了。就像 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);
推荐阅读
- python - 使用递归/获取“无”附加到我的输出
- python - 如何在 python 中使用 *args 进行划分?
- flutter - Flutter 需要两次点击/点击来改变 `ontap` 颜色变化
- python - 如何过滤数据框行并将总和保存在新行中?
- javascript - 我正在尝试制作一个看起来已经完成的图像过滤器,但唯一的是当我加载页面时它是空白的,直到我点击过滤器列表
- c++ - C ++ OpenGL纹理未按应有的方式渲染
- php - 你能在 php 文件中回显 php
- javascript - 本地主机中的 chrome 支持我的 Web 共享 API,但托管我的网站后不支持?
- java - 如何将循环中输入的值调用到Process中,这是一个JAVA SRT程序
- pyqt5 - 具有边框半径属性的 QPushButton 不起作用