我正在做一个项目,其中某些句子需要不可见。用户应该能够通过单击句子占据的空间来使它们可见。为什么单击空白区域后文本不可见?
document.getElementsByTagName("span")[0].style.visibility = "hidden"
document.getElementsByTagName("span")[0].addEventListener("click", toggle)
function toggle(){
this.style.visibility = "visible"
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<span> Hi. How are you? </span>
<span> I am fine </span>
</body>
</html>
最佳答案
你不能点击不可见的东西。使用 opacity
而不是 visibility
.
此外,不要使用内联样式。只需创建一个 CSS 类并根据需要使用 .classList
API 添加/删除它.
最后,this document.getElementsByTagName("span")[0]
is really, really bad code .
// Use .querySelector() and .querySelectorAll() to get elements and collections
// of elements when necessary.
// Set up your event on a parent of all the elements that need the
// same event handler. When a descendant within the parent fires
// an event, that event will bubble up to the parent and be handled
// there. This is called "event delegation"
document.addEventListener("click", toggle);
function toggle(event){
// Check to see if the event was triggered by an element
// that you care about. event.target represents the element
// that actually triggered the event
if(event.target.classList.contains("hideable")){
// Just toggle (or add depending on what you want) the use of the CSS class
//event.target.classList.add("hidden");
event.target.classList.toggle("hidden");
}
}
/* Use CSS classes whenever possible.
They are easier to set up and manage. */
.hidden { opacity:0; }
.hideable { cursor:pointer; }
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<span>My name is: </span>
<span class="hideable hidden">Scott. </span>
<span> I am fine. </span>
<span class="hideable hidden">How are you? </span>
<span> Have a great day! </span>
</body>
</html>
关于javascript - 使用 Javascript 在隐藏文本和可见文本之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59038707/