我刚刚开始使用JS(已经有一段时间了)所以我有点生疏了!当按下按钮时,我正试图使输入成为焦点。任何人都可以解释为什么这可以在片段中工作但不在我的文档中吗?
document.getElementById('Search_Button').addEventListener('click', function ()
{
document.getElementById('Search_Input').focus();
});
<input type="checkbox" id="Search_Button" />
<label for="Search_Button"><div id="Search_Bar_Dismiss_Box"></div></label>
<div id="Search_Box">
<input type="search" name="Search" id="Search_Input" placeholder="Search" />
<label for="Search_Button"><img src="SVG/Back_Arrow.svg" id="Cancel_Search"></label>
</div>
这是我的整个文件:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
document.getElementById('Search_Button').addEventListener('click', function()
{
document.getElementById('Search_Input').focus();
});
</script>
</head>
<body>
<input type="checkbox" id="Search_Button" /> <!-- Opens Search Bar -->
<label for="Search_Button"><div id="Search_Bar_Dismiss_Box"></div></label>
<div id="Search_Box">
<input type="search" name="Search" id="Search_Input" placeholder="Search" />
<label for="Search_Button"><img src="SVG/Back_Arrow.svg" id="Cancel_Search"></label>
</div>
</body>
</html>
答案 0 :(得分:2)
将您的代码放在 window.onload 函数
上window.onload = function()
{
document.getElementById('Search_Button').addEventListener('click', function ()
{
document.getElementById('Search_Input').focus();
});
};
希望有所帮助
答案 1 :(得分:1)
工作代码:在页脚部分添加脚本
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="checkbox" id="Search_Button" /> <!-- Opens Search Bar -->
<!-- SEARCH BAR -->
<label for="Search_Button">
<div id="Search_Bar_Dismiss_Box">
</div> <!-- Search Bar Dismiss Box -->
</label> <!-- Dismisses the search bar -->
<div id="Search_Box">
<input type="search" name="Search" id="Search_Input" placeholder="Search" />
<label for="Search_Button">
<img src="SVG/Back_Arrow.svg" id="Cancel_Search">
</label>
</div> <!-- Search Box -->
<script type="text/javascript">
document.getElementById('Search_Button').addEventListener('click', function (){
document.getElementById('Search_Input').focus();
});
</script>
</body>
</html>