Come simulare un clic per fare in modo che l'input corrente non si focalizzi con JavaScript

StackOverflow https://stackoverflow.com/questions/220488

  •  03-07-2019
  •  | 
  •  

Domanda

Ho un input che in alcuni punti sembra avere il focus. Se l'utente fa clic su " background " della pagina, l'ingresso perde la sua attenzione. Stavo cercando di simulare il clic sullo sfondo con il seguente codice, ma questo non funziona (noterai che l'input ha ancora lo stato attivo). Qualsiasi suggerimento su come scrivere il codice che simula un clic sullo "sfondo" della pagina?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/yahoo/yahoo-min.js" ></script>
        <script type="text/javascript" src="http://yui.yahooapis.com/2.6.0/build/event/event-min.js" ></script>
        <script type="text/javascript">
            YAHOO.util.Event.onDOMReady(function() {
                document.getElementById("input").focus();    
                document.getElementById("main").focus();    
            });
        </script>
    </head>
    <body>
        <div id="main">
            <form action="/">
                <p>
                    <input type="text" id="input"/>
                </p>
            </form>
        </div>
    </body>
</html>
È stato utile?

Soluzione

Immagino che usare blur () farebbe il trucco:

<script type="text/javascript">
    YAHOO.util.Event.onDOMReady(function() {
        document.getElementById("input").focus();    
        document.getElementById("input").blur();    
    });
</script>

Altri suggerimenti

Prova a utilizzare l'evento blur . Se stai usando jQuery c'è un metodo che puoi chiamare sull'oggetto DOM per generare questo evento. Il metodo blur () dovrebbe funzionare anche senza jQuery.

http://docs.jquery.com/Events/blur

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top