【问题标题】:Input focus and blur输入焦点和模糊
【发布时间】:2017-01-01 16:26:50
【问题描述】:

我有这个代码https://fiddle.jshell.net/cabeqaky/26/ 问题是如何在first div click 上进行设置,输入获取焦点并打开 second div click 输入失去焦点。怎么做? :)

HTML

<input class="inp" type="text">
<div class="box"></div>

CSS

.box{
width:50px;
height:50px;
background-color:green;
margin-top:10px;
border:1px black solid;
cursor:pointer
}

【问题讨论】:

    标签: javascript jquery input focus blur


    【解决方案1】:

    您可以在 div 上使用 mousedown 事件并检查输入是否具有焦点。 e.preventDefault() 用于避免鼠标按下事件时焦点在 div 元素上。

    $("div").on("mousedown",function(e){  
      e.preventDefault();
      if($(".inp:focus").is(':focus'))
        $(".inp").blur();
      else
       $(".inp").focus();
    })
    .box{
    width:50px;
    height:50px;
    background-color:green;
    margin-top:10px;
    border:1px black solid;
    cursor:pointer
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <input class="inp" type="text">
    <div class="box"></div>

    【讨论】:

    • 但这里有个问题,它只适用于 jquery 2.1.1,对吧?
    • 也可以修改为与其他版本一起使用。您正在使用什么版本?即使需要更改一些代码,逻辑也不会改变。
    • 最新版本 3.1.1 :)
    • @art 3.1.1 不需要更改。更新了示例
    • 哦,对不起,一开始没看到你改了html,对不起,是的,当然可以,谢谢,新年快乐;)
    【解决方案2】:
    $(document).ready(function(){
        $("div.box").data("toggle", 0);
        $("div.box").click(function(){
            var toggle = $("div.box").data("toggle");
            if(toggle === 0){
                $("div.box").data("toggle", 1);
                $("input.inp").focus();
            } else {
                $("div.box").data("toggle", 0);
                $("input.inp").blur();
            }
        });
    });
    

    【讨论】:

    • 你是不是把 JQuery 库放在 Head 中像:
    【解决方案3】:

    在 div 上使用 javascript 函数:

    var focus = false;
    
    function toggleFocus() {
      focus = !focus;
      if (focus) {
        document.getElementById("focusedInput").focus();
      }
    }
    <input class="inp" id="focusedInput" type="text">
    <div class="box" onclick='toggleFocus()'></div>

    【讨论】:

      【解决方案4】:

       $(".box").click(function(){
          document.getElementsByClassName("inp")[0].focus();
      
      })
          .box{
          width:50px;
          height:50px;
          background-color:green;
          margin-top:10px;
          border:1px black solid;
          cursor:pointer
          }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      
          <input class="inp" type="text">
          <div class="box"></div>

      【讨论】:

        猜你喜欢
        • 2012-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-08
        相关资源
        最近更新 更多