【发布时间】:2019-05-30 11:47:42
【问题描述】:
我目前正在使用 reactjs 做一个项目,我想使用链接标签一一显示错误消息,此链接可能引用 div、p、输入、按钮任何 html 元素。
点击链接,相应的html元素应该被聚焦并显示出来。
现在的问题是,有时目标元素位于隐藏的选项卡或 div 中,我无法聚焦它
例如在一个非活动选项卡中,我有没有机会让它处于活动状态,然后聚焦元素?
这是一个简单的例子:
function openCity(cityName) {
var i;
var x = document.getElementsByClassName("city");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById(cityName).style.display = "block";
}
const findIt = () => {
document
.getElementById("target")
.focus();
};
.w3-container {
margin-top:16px;
margin-bottom:16px;
}
.w3-container:after,.w3-container:before {
content:"";
display:table;
clear:both
}
.w3-bar .w3-bar-item{
padding:8px 16px;
float:left;
width:auto;
border:none;
display:block;
outline:0
}
.w3-black{
color:#fff!important;
background-color:#000!important
}
.w3-button{
border:none;
display:inline-block;
padding:8px 16px;
vertical-align:middle;
overflow:hidden;
text-decoration:none;
color:inherit;
background-color:inherit;
text-align:center;
cursor:pointer;
white-space:nowrap
}
<div class="w3-container">
<h2> 3 Tabs below :</h2>
</div>
<div class="w3-bar w3-black">
<button class="w3-bar-item w3-button" onclick="openCity('London')">
London
</button>
<button class="w3-bar-item w3-button" onclick="openCity('Paris')">
Paris
</button>
<button class="w3-bar-item w3-button" onclick="openCity('Tokyo')">
Tokyo
</button>
</div>
<div id="London" class="w3-container city">
<h2>London</h2>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="w3-container city" style="display:none">
<h2>Paris</h2>
<input value="im ere ry o ind" id="target" />
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="w3-container city" style="display:none">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
</div>
<br /><br /><br />
<button onclick="findIt()">click to focus input inside PARIS tab</button>
所以它只有在巴黎活跃时才有效
【问题讨论】:
标签: javascript html css reactjs