我的javascript函数无法运行所有代码

时间:2018-07-16 09:30:10

标签: javascript css

如果写成这样,请帮我解决:

function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
    document.getElementById("name-page").style.width = "738px";
    document.getElementById("news").style.marginLeft = "0";
    document.getElementById("ida").style.marginLeft = "0";
}

function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft= "0";
    document.getElementById("name-page").style.width = "930px";
    document.getElementById("news").style.marginLeft = "125px";
    document.getElementById("ida").style.marginLeft = "125px";
}

样式id=news可以更改,但是样式id=ida不能更改 如果这样写:

function openNav() {
    document.getElementById("mySidenav").style.width = "250px";
    document.getElementById("main").style.marginLeft = "250px";
    document.getElementById("name-page").style.width = "738px";
    document.getElementById("ida").style.marginLeft = "0";
    document.getElementById("news").style.marginLeft = "0";
}


function closeNav() {
    document.getElementById("mySidenav").style.width = "0";
    document.getElementById("main").style.marginLeft= "0";
    document.getElementById("name-page").style.width = "930px";
    document.getElementById("ida").style.marginLeft = "125px";
    document.getElementById("news").style.marginLeft = "125px";
}

样式id=news无法更改,但是样式id=ida会更改

请帮助我,抱歉我的语言

1 个答案:

答案 0 :(得分:1)

在设置属性之前检查元素是否存在:

...
if(document.getElementById("news")) {
    document.getElementById("news").style.marginLeft = "0";
}    
if(document.getElementById("ida")) {
    document.getElementById("ida").style.marginLeft = "0";
}
...