繁体   English   中英

JS .focus()在代码段中有效,但不在文档中

[英]JS .focus() working in snippet but not in document

我刚刚又开始使用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>

将您的代码放在window.onload函数上

window.onload = function() 
{
    document.getElementById('Search_Button').addEventListener('click', function ()            
    {
        document.getElementById('Search_Input').focus();
    });
};

希望能帮助到你

工作代码:在页脚部分添加脚本

<!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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM