Autofocus only working on page refresh

荒凉一梦 提交于 2020-05-29 06:18:43

问题


I have a form which is in a popup, I've set the autofocus attribute autofocus="autofocus" but it is not focusing when the form loads however it will focus if you refresh the page. The form is inserted into a div.

Form Sample:

First Name:<input type="text" name="fname" placeholder="First Name" class="userField" autofocus="autofocus" id="firstNameUserField" value="<?php 
    if(isset($_SESSION['firstname'])){
       echo trim($_SESSION['firstname']);
    }
  ?>">

Div form is inserted into:

  <div class="main">
    <a href="#x" class="overlay" id="detail_form"></a>
    <div class="popup">
      <div id="detailFormPopup"></div>
      <a class="close" id="logClose"href="#close"></a>
    </div>
  </div>

Form is shown if user is logged in and clicks their username:

if(isset($_SESSION['username'])){
          echo "<a href='#detail_form' class='navlinks' id='navUser'>".$_SESSION['username']."</a></h3>";
        }

回答1:


autofocus will apply only for elements initially in the page, not elements loaded with Javascript.

You can force the focus in the Javascript code that you use to render the SimpleModal, add it to the onShow event:

$('#firstNameUserField').focus();

You didn't include the Javascript used to open the popup in your question, so this is just a general example:

$("#popupEl").modal({onShow: function (dialog) {
 $('#firstNameUserField').focus();
}});



回答2:


To solve the issue of "Autofocus only working on page refresh"

Do the following changes in your files:-

//In module.ts file 

import { AutofocusModule } from 'angular-autofocus-fix';

@NgModule({
imports: [
AutofocusModule
],

//In package.json file add the dependencies as:- 

    "dependencies": {
    "angular-autofocus-fix": "^0.1.0"
}


来源:https://stackoverflow.com/questions/15800058/autofocus-only-working-on-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!