如何使用javascript模糊输入字段或做出反应?

我是编程新手,我想模糊“文本”类型的输入元素。

我要做什么? 我在一个react组件中有一个输入元素,这就是使用querySelector获得焦点的原因。现在,在其他组件中,我想从同一输入元素中删除焦点。

我尝试将querySelector与blur方法一起使用。但是没用。

下面是我的代码,

 class Popup extends React.PureComponent {
     render() {
         return {
             <OverlayComponent 
                    <input
                        type="text"/>
             </OverlayComponent>
         }
     }
 }

 class OverlayComponent extends React.PureComponent {
     constructor(props) {
         super(props);
         this.element = document.createElement('div');
     }
     componentDidmount() {
         const input = this.element.querySelector
                       ('input:not([type=button]),input:not([type=submit])
                       :not([type=file]),textarea');
         input && input.focus();
     }

     render() {
         return {
             //something
         }
     }
 }


 class Anothercomponent extends React.PureComponent {
     componentDidmount() {
          const input = document.querySelector
                        ('input:not([type=button]),input:not([type=submit])
                        :not([type=file]),textarea');
          input && input.blur();
     }
 }

输入元素将焦点放在overlyacomponent上,但不会删除AnotherComponent中输入元素的焦点。OverlayComponent和AnotherComponent在同一页面中可见。

有人可以让我知道我要去哪里了。谢谢。

编辑: 如何在AnotherComponent中使用setTimeout方法从输入元素中删除焦点。

jiajiadelan 回答:如何使用javascript模糊输入字段或做出反应?

我会在常规javascript中执行以下操作:

function BlurTheThing() {
     var TheThing = document.getElementsByClassName(".ClassNameOfTheThing").click(function) {
        TheThing.blur();
     };
}

或者如果您不反对使用jQuery,则此

function BlurTheThing() {
    $(".ClassNameOfTheThing").click(function () { 
        $(this).blur();
    }
}

自从我被展示以来,我一直使用的一个技巧是,确保您选择正确的东西,尝试随即使用javascript或jQuery更改要选择的东西的边框颜色。从您要单击的内容开始:

function BlurTheThing() {
    $(".ClassNameOfTheThing").click(function () { 
        // get the element you just clicked
        var TheThingYoureTryingToSelect = $(this);
        // and set it's border to a color that will stand out
        TheThingYoureTryingToSelect.css("border","thin solid red");
    }
}

确保在所需元素上更改边框颜色,然后再次执行相同的操作,只是这次根据需要选择元素的父级(或子级或同级):

function BlurTheThing() {
    $(".ClassNameOfTheThing").click(function () { 
        // get the parent of the element you just clicked
        var TheThingYoureTryingToSelect = $(this).parent();
        // and set it's border to a color that will stand out
        TheThingYoureTryingToSelect.css("border","thin solid red");
    }
}

您可以将它们堆叠并继续前进,例如$(this).parent().parent()$(this).parent().sibling()等。通过这种方式,您可以浏览DOM并确保选择了要选择的内容。或者,您可以尝试使用.find(".ClassNameOfTheThing"),看看是否适合您。

无论哪种方式,一旦确定要选择的内容就可以使用blur()

,

为什么要使用查询选择器?

React并不是真正为使用Vanilla dom操作而构建的。

您应使用react dom操作,例如使用状态或道具更新输入。

您可能还想使用钩子来保持方便(这使您可以摆脱类并在同一上下文中具有多个函数(每个函数返回JSX),每个函数都有自己的“状态”)。

本文链接:https://www.f2er.com/3164709.html

大家都在问