尝试在单击按钮时显示div [英] Trying to make a div appear when a button is clicked

查看:60
本文介绍了尝试在单击按钮时显示div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码,首先,当我将其显示值设置为"none"时,为什么会显示div;还有其他什么我需要修复才能使div在单击按钮时显示吗?谢谢

Here is the code , first of all why is the div showing up when I set it's display value to "none"; and is there anythign I else I need to fix to make the div appear when I click the button? Thanks

HTML

<button onclick="openTest()">Try it</button>

<div id="test">
</div>

CSS

#test {
    width: 500px;
    height: 500px;
    background-color: lightblue;
}

JS

document.getElementById("test").style.display ="none";

function openTest() {
    document.getElementById("test").style.display = "block";
}

推荐答案

不要使用内联javascript-而是附加一个事件侦听器,并确保将您的代码放在 window.onload = function(){}中或紧接在</body> 标记之前.这样,您可以在脚本运行时找到您的元素. 尝试此代码 :

Don't use inline javascript - attach an event listener instead and make sure to place your code either in window.onload = function() {} or right before the closing </body> tag. That way your elements will be found when the script runs. Try this code:

HTML:

<button id="btn">Try it</button>

<div id="test">
</div>

JS:

document.getElementById("test").style.display ="none";

function openTest() {
    document.getElementById("test").style.display = "block";
}

document.getElementById('btn').addEventListener('click', openTest);

这篇关于尝试在单击按钮时显示div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆