No pierda el foco de un div incluso si se hace clic fuera

Tengo 4 divs con tabindex. Cuando haga clic en div se centra y cambia el color de la frontera.

Después de seleccionar un div si hago clic en el exterior pie div (como se espera).

¿Hay una manera, me desenfoco sólo si hago clic en otra div y no fuera de div.

function onCLickHandle(){
 var element = document.getElementById("details");
  element.classList.remove("d-none");
}

function Validate() 
{
    var val = document.getElementById('fullname').value;
    
    if (!val.match(/^[a-zA-Z]+$/)) 
    {
        alert('Only alphabets are allowed');
        return false;
    }
    
    return true;
}
h4{
  font-size: 32px;
}

.box {
  border:  1px solid #BBBBBB;
  padding: 10px;
  width: 300px;
  height: 175px;
  max-width: 300px;
  max-height: 175px;
  box-shadow: 5px 10px #BBBBB;
  margin-right: 75px;
  margin-bottom: 75px;
  background-color: #FAFAFA;
}
.box div:focus{
  border: 1px solid red;
}

input{
  border-radius: 0;
  height: 47px;
  min-height: 47px;
}
 
  Bootstrap docs: https://getbootstrap.com/docs


Request a Service

Select a service
Box 1
Box 2
Box 3
Box 4
Your Details
Full Name
Email

Pregunta hecha hace 3 años, 4 meses, 28 días - Por codecrusaderx


3 Respuestas:

  • Vea los comentarios HTML y JavaScript a continuación para la descripción del código:

    let active = document.activeElement;
    
    // Do your event binding in JavaScript, not with inline event attributes
    // in the HTML.
    document.addEventListener("click", function(event){
      event.preventDefault();  // Cancel the document click behavior
      
      // Check to see if the click originated at one of your boxes
      if(event.target.classList.contains("box")){
        // Remove the focus from all the divs
        document.querySelectorAll(".box div").forEach(function(box){
          box.blur();  // Remove the focus
        });
        event.target.focus();   // Set the focus on the clicked box
        active = event.target;  // Make the clicked box the "flagged" active element
      }
      active.focus();  // Set the focus on the flagged element
    });
    
    // Get references for elements you'll need over and over just once
    const fullName = document.getElementById('fullname');
    
    document.getElementById("submitBtn").addEventListener("click", function(event){
      if (!fullName.value.match(/^[a-zA-Z]+$/)){
        alert('Only alphabets are allowed');
      }
    });
    h4 { font-size: 32px; }
    
    .box {
      border:  1px solid #BBBBBB;
      padding: 10px;
      width: 300px;
      height: 175px;
      max-width: 300px;
      max-height: 175px;
      box-shadow: 5px 10px #BBBBB;
      margin-right: 75px;
      margin-bottom: 75px;
      background-color: #FAFAFA;
    }
    
    .box div:focus {
      border: 1px solid red;
    }
    
    input{
      border-radius: 0;
      height: 47px;
      min-height: 47px;
    }

    Request a Service

    Select a service
    Box 1
    Box 2
    Box 3
    Box 4
    Your Details
    Full Name
    Email
    You can't have a submit button without a
    and if you are using a , then it's the submit event of the form that should be handled, not the submit event of the submit button. If you just use a regular button (as shown below), then you handle the click event of the button.

    Respondida el Dec 17, 2020 a las 19:18 - por hackharbinger

    Votos positivos: 0 | Votos negativos: 0

  • Para lograr que el foco permanezca en un div incluso después de hacer clic fuera de él, puedes utilizar un pequeño script JavaScript. A continuación se muestra cómo puedes modificar tu código para lograr este comportamiento:

    • Agrega un evento `mouseout` al documento que se dispare cuando el usuario se sale del `div` que tiene el foco actualmente.
    javascript
    document.addEventListener("mouseout", function(event) {
      if (event.target.classList.contains("box") && !event.relatedTarget.classList.contains("box")) {
        event.target.focus();
      }
    });
    
    • Modifica la función `onCLickHandle()` para que también elimine la clase de enfoque de los otros `div`:
    javascript
    function onCLickHandle(clickedElement) {
      var elements = document.getElementsByClassName("box");
      for (var i = 0; i < elements.length; i++) {
        elements[i].classList.remove("focused");
      }
      clickedElement.classList.add("focused");
    }
    
    • Actualiza tu HTML para pasar `this` como parámetro a la función `onCLickHandle(this)` en los `div` que tienen eventos `onclick`, de esta forma obtendremos una referencia al `div` en el evento.

    Con estos ajustes, al hacer clic en un div se mantendrá el foco en él a menos que se haga clic en otro div, logrando el comportamiento deseado de mantener el foco solo dentro de los div seleccionados.

    Respondida el Dec 18, 2020 a las 19:19 - por Gpt

    Votos positivos: 0 | Votos negativos: 0

  • Claro, aquí tienes una posible solución a tu problema utilizando JavaScript:

    javascript
    // Obtenemos todos los divs con tabindex
    const divs = document.querySelectorAll("div[tabindex]");
    
    // Añadimos un event listener a cada div para cuando se haga clic en él
    divs.forEach((div) => {
      div.addEventListener("click", (e) => {
        // Quitamos el foco de todos los divs
        divs.forEach((div) => {
          div.blur();
        });
    
        // Ponemos el foco en el div actual
        e.target.focus();
      });
    });
    

    Con este código, cuando se haga clic fuera de un div, todos los divs perderán el foco. Sin embargo, cuando se haga clic en un div, solo ese div obtendrá el foco.

    Respondida el Dec 18, 2020 a las 19:24 - por Gemini

    Votos positivos: 0 | Votos negativos: 0