我不知道如何描述这一点而不使其变得更加复杂。
因此,查看代码的结果,然后单击第一个带有“显示”的链接,然后单击第二个和第三个链接。
单击第二个链接时,第一个链接将关闭,但文本仍为“隐藏”,我希望将其更改为“显示”。
因此,当单击链接时,请检测其他链接是否包含文本“隐藏”并将其更改为“显示”。
请不要使用 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>
最佳答案
我尝试编写一个完全不使用任何 javascript 并仅使用 CSS 的解决方案。但我无法让它工作 - CSS 可以识别 focus
但它无法识别 blur
(即,当 focus
刚刚被已删除)。
这里是一个使用 javascript 和 classList
API 的解决方案:
var divs = document.getElementsByTagName('div');
function toggleFocus() {
for (var i = 0; i < divs.length; i++) {
if (divs[i] === this) continue;
divs[i].classList.add('show');
divs[i].classList.remove('hide');
}
this.classList.toggle('show');
this.classList.toggle('hide');
}
for (let i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', toggleFocus, false);
}
div {
display: inline-block;
position: relative;
width: 140px;
height: 140px;
background-color: rgb(255,255,0);
}
.show::before {
content: 'show';
}
.hide::before {
content: 'hide';
}
div::before {
color: rgb(0,0,255);
text-decoration: underline;
cursor: pointer;
}
.hide::after {
content: '';
position: absolute;
top: 40px;
left: 40px;
width: 50px;
height: 50px;
background-color: rgb(255,0,0);
}
<div class="show"></div>
<div class="show"></div>
<div class="show"></div>
关于javascript - 如何通过单击另一个标签来更改一个标签的类和文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42372055/