我不知道如何描述这一点,而不会使它更复杂。
所以看看代码的结果,点击第一个链接的“显示”,然后第二个和第三个。
当第二个链接被点击时,第一个关闭,但文本仍然是“隐藏”,我希望它更改为“显示”。
因此,点击链接时,检测是否有其他链接有文本“隐藏”,并将其更改为“显示”。
并请没有jQuery的...如何通过点击另一个标签来更改一个标签的类和文本?
document.getElementsByClassName("show")[0].onclick = function() {
var x = document.getElementsByClassName("hide")[0];
var y = document.getElementsByClassName("show")[0];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[1].onclick = function() {
var x = document.getElementsByClassName("hide")[1];
var y = document.getElementsByClassName("show")[1];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
document.getElementsByClassName("show")[2].onclick = function() {
var x = document.getElementsByClassName("hide")[2];
var y = document.getElementsByClassName("show")[2];
if (x.classList.contains("visible")) {
x.classList.remove("visible");
y.textContent = "Show";
} else {
closeOther();
x.classList.add("visible");
y.textContent = "Hide";
}
};
function closeOther() {
var visible = document.querySelectorAll(".visible"),
i, l = visible.length;
for (i = 0; i < l; ++i) {
visible[i].classList.remove("visible");
}
}
.style {
background-color: yellow;
width: 200px;
height: 200px;
display: inline-block;
}
.hide {
background-color: red;
width: 50px;
height: 50px;
display: none;
position: relative;
top: 50px;
left: 50px;
}
.hide.visible {
display: block;
}
<div class="style">
<a href="#" class="show">Show</a>
<div class="hide">
</div>
</div>
<div class="style">
<a href="#" class="show">Show</a>
<div class="hide">
</div>
</div>
<div class="style">
<a href="#" class="show">Show</a>
<div class="hide">
</div>
</div>
可能的复制http://stackoverflow.com/questions/36162805/toggle-radio-input -using-css-only – LGSon
在上面的帖子中有几种方法可以使用CSS来做 – LGSon
不是重复的,因为我正在练习javascript,并且想要在js中只使用它的方法... – mpasd