javascript 动态更改显示属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3758225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:09:35  来源:igfitidea点击:

Changing display property dynamically

javascripthtmlcss

提问by Miya

I want to change the style:display property (none or block) of my div (displaydiv) according to the value of a global variable (disp). I want to check the value of this variable on page load and set the styel: display according to the value disp.

我想根据全局变量 (disp) 的值更改我的 div (displaydiv) 的 style:display 属性(none 或 block)。我想在页面加载时检查这个变量的值,并根据值 disp 设置 styel: display。

i set the value of disp as "none" in javascript.

我在 javascript 中将 disp 的值设置为“none”。

i want to change the value within HTML TAG

我想更改 HTML TAG 中的值

But this div is always visible. Please help me

但是这个 div 总是可见的。请帮我

回答by Stephan Muller

<script>
function hidemydiv() {
 if(disp == 'none') document.getElementById('displaydiv').style.display = 'none';
}
</script>

<body onload="hidemydiv()">
<div id="displaydiv">
    Lorem ipsum dolor sith amet
</div>
</body>

I just wonder what kind of global variable disp is. Is it in javascript? PHP? Where/when/how do you set it?

我只是想知道什么样的全局变量 disp 是。它是在 javascript 中吗?PHP?你在哪里/何时/如何设置它?

回答by annakata

We can't tell without code but it sounds very much like you're executing your change-style JS inline before the target DIV has loaded.

没有代码我们无法判断,但这听起来很像您在目标 DIV 加载之前内联执行更改样式的 JS。

Does your browser report errors on the page?

您的浏览器是否报告页面错误?

Is your JS code bound to the onload event somehow?

您的 JS 代码是否以某种方式绑定到 onload 事件?

Is the style actually applied but overidden (check with firebug)?

样式是否实际应用但被覆盖(检查萤火虫)?

回答by Q_Mlilo

Attach a function to the window onload event.

将函数附加到窗口 onload 事件。

window.onload = function () {
    var elem = document.getElementById(divId);

    if (disp === "none") {
        elem.style.display = "none";
    }
    else {
        elem.style.display = "block";
    }
};