chrome extension popup textarea focus

笑着哭i 提交于 2019-12-20 01:45:26

问题


It seems that i cannot call focus() on a textarea of my chrome extensions popup when it gets opened / after ondomready.

i have something like that in popup.js :

$(document).ready(function () {
   console.log($("#moped-text"));
   $('textarea').focus();   
   $('.container').css("color", "red");
});

i reference it in popup.html like that:

<html>
  <head>

    <link rel="stylesheet" href="css/content.css" type="text/css">

    <script type="text/javascript" src="js/lib/jquery.js"></script>
    <script type="text/javascript" src="js/popup.js"></script>
  </head>
 <body>
       <div class="container">
            <textarea name="newText"></textarea>
       </div>     
 </body>

The css-change works, the focus() does not!

When i debug the popup and type $('textarea').focus(); in the console, it works. Also events added inside the ready-callback are bound successfully.

Any help highly appreciated!


回答1:


i still don't know, why the focus is not set at the first place, but a simple timeout does the job :)

setTimeout(function() {
  $('#moped-text').focus();
}, 500);



回答2:


Workaround for Chrome 18 (found here)

if(location.search !== "?foo")
{
  location.search = "?foo";
  throw new Error;  // load everything on the next page;
                    // stop execution on this page
}

Works for me!




回答3:


You have div with class "container" not id. So use this instead:

$('.container').css("color", "red");



回答4:


I use this to focus.

My element has "autofocus" as an attribute. When the form is loaded, the element with the attribute "autofocus" gets the focus.

.directive('autofocus', ['$timeout', function($timeout) { return { restrict: 'A', link : function($scope, $element) { $timeout(function() { $element[0].focus(); }); } } }])




回答5:


You can simply use <textarea name="newText" autofocus></textarea>.



来源:https://stackoverflow.com/questions/9646772/chrome-extension-popup-textarea-focus

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