>  기사  >  웹 프론트엔드  >  onclick과 onblur_javascript 기술 간의 충돌에 대한 빠른 솔루션

onclick과 onblur_javascript 기술 간의 충돌에 대한 빠른 솔루션

WBOY
WBOY원래의
2016-05-16 15:03:151835검색

시나 홈페이지 검색창에 ajax를 이용한 드롭다운 박스가 있습니다. 검색 상자의 값이 이 항목으로 변경되고 드롭다운 상자가 사라지도록 드롭다운 상자에서 항목을 클릭하는 효과를 달성해야 합니다. 그러나 동시에 다른 곳을 클릭하면 드롭다운이 사라집니다. 상자도 사라집니다. 대략 그림과 같습니다:

onclick과 onblur_javascript 기술 간의 충돌에 대한 빠른 솔루션


드롭다운 상자를 숨기기 위해 onblur와 onclick을 동시에 사용하지만 더 큰 문제가 발생합니다. Onblur는 너무 강력하고 검색 상자에서 콘텐츠를 얻을 수 없습니다. 클릭한 항목의 이것이 우리가 해결하고 싶은 onclick과 onblur 사이의 충돌입니다.

이 문제에 대응하여 두 가지 해결책을 소개합니다.

1. setTimeout을 사용하여 onblur 시간의 실행을 지연시켜 onclick이 실행된 후에 onblur가 실행되도록 합니다. (setTimeout의 시간 설정은 100ms 이상이어야 하며, 그렇지 않으면 여전히 작동하지 않습니다.) 샘플 코드는 다음과 같습니다.

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    *{ margin: 0; padding: 0; list-style: none; }
    form{
      width:500px;
      margin:0 auto;
      position:relative;
      zoom:1;
    }
    form:after{
      clear:both;
      content:"";
      display:block;
    }
    .text{
      float:left;
      border:1px solid #cccccc;
      padding-left:14px;
      width:300px;
      height:34px;
      line-height:34px;
      font-size:14px;
    }
    .button{
      width:50px;
      height:34px;
      border:1px solid #cccccc;
      line-height:34px;
      font-size:14px;
      color:#ffffff;
      background:#ff8400;
    }
    ul{
      position:absolute;
      top:36px;
      left:0;
      width:300px;
      border-right:1px solid #cccccc;
      border-left:1px solid #cccccc;
      background:green;
      display:none;
    }
    li{
      font-size:14px;
      line-height:34px;
      height:34px;
      color:#000000;
      border-bottom:1px solid #cccccc;
    }
    li:hover{
      background:yellow;
      color:red;
      cursor:pointer;
    }
  </style>
  <script>
    window.onload=function(){
      var oText=document.getElementById('text');
      var oUl=document.getElementById('ul');
      var aLi=oUl.getElementsByTagName('li');
      var timer=null;
      oText.onfocus=function(){
        this.value='';
        oUl.style.display='block';
        for(var i=0;i<aLi.length;i++){
          aLi[i].onclick=function(){
            clearTimeout(timer);
            oText.value=this.innerHTML;
            oUl.style.display='none';
          };
        }
      };
      oText.onblur=function(){
        timer=setTimeout(function(){
          oUl.style.display='none';
          if(!oText.value){
            oText.value='请输入关键字';
          }
        },120);
      };
    };
  </script>    
</head>
<body>
<form>
  <input type="text" value="请输入关键字" id="text" class="text"/>
  <input type="button" value="搜索" class="button"/>
  <ul id="ul">
    <li>返回窗口是否已被关闭</li>
    <li>返回窗口的文档显示区的高度</li>
    <li>返回窗口的文档显示区的宽度。</li>
    <li>设置或返回窗口的名称。</li>
    <li>返回窗口的外部高度。</li>
  </ul>
</form>
  
</body>
</html>

2. 드롭다운 상자 기능을 숨기려면 onblur 대신 document.onmousedown을 사용하세요

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    *{ margin: 0; padding: 0; list-style: none; }
    form{
      width:500px;
      margin:0 auto;
      position:relative;
      zoom:1;
    }
    form:after{
      clear:both;
      content:"";
      display:block;
    }
    .text{
      float:left;
      border:1px solid #cccccc;
      padding-left:14px;
      width:300px;
      height:34px;
      line-height:34px;
      font-size:14px;
    }
    .button{
      width:50px;
      height:34px;
      border:1px solid #cccccc;
      line-height:34px;
      font-size:14px;
      color:#ffffff;
      background:#ff8400;
    }
    ul{
      position:absolute;
      top:36px;
      left:0;
      width:300px;
      border-right:1px solid #cccccc;
      border-left:1px solid #cccccc;
      background:green;
      display:none;
    }
    li{
      font-size:14px;
      line-height:34px;
      height:34px;
      color:#000000;
      border-bottom:1px solid #cccccc;
    }
    li:hover{
      background:yellow;
      color:red;
      cursor:pointer;
    }
  </style>
  <script>
    window.onload=function(){
      var oText=document.getElementById('text');
      var oUl=document.getElementById('ul');
      var aLi=oUl.getElementsByTagName('li');
      var timer=null;
      oText.onfocus=function(){
        this.value='';
        oUl.style.display='block';
        for(var i=0;i<aLi.length;i++){
          aLi[i].onclick=function(){
            clearTimeout(timer);
            oText.value=this.innerHTML;
            oUl.style.display='none';
          };
        }
      };
      
      document.onmousedown=function(ev){
        var oEvent=ev||event;
        var target=oEvent.target||oEvent.srcElement;
          if(target.parentNode!==oUl&&target!==oText){
            oUl.style.display='none';
          }
        
      };
      oText.onblur=function(){
        if(!oText.value){
          oText.value='请输入关键字';
        }  
      };
    };
  </script>    
</head>
<body>
<form>
  <input type="text" value="请输入关键字" id="text" class="text"/>
  <input type="button" value="搜索" class="button"/>
  <ul id="ul">
    <li>返回窗口是否已被关闭</li>
    <li>返回窗口的文档显示区的高度</li>
    <li>返回窗口的文档显示区的宽度。</li>
    <li>设置或返回窗口的名称。</li>
    <li>返回窗口的外部高度。</li>
  </ul>
</form>
  
</body>
</html>

위에 언급된 onclick 및 onblur 충돌 문제에 대한 빠른 해결 방법은 편집자가 공유한 모든 내용을 참고할 수 있기를 바라며, Script Home을 지원해 주시길 바랍니다.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.