日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

React - 判斷焦點(diǎn)是否在某個元素上

作者:WHOVENLY 更新時間: 2022-10-11 編程語言

在工作中遇到一個這個小功能,就是當(dāng)用戶從A輸入框中失焦后,要去判斷當(dāng)前的焦點(diǎn)是否在B輸入框中,如果是的話需要做一些特殊操作.其實(shí)實(shí)現(xiàn)起來很簡單,就是使用ref配合document.activeElement方法即可實(shí)現(xiàn),以下是實(shí)現(xiàn)的具體邏輯

import React from "react";
// 當(dāng)在A輸入框中失焦之后,要判斷當(dāng)前焦點(diǎn)是否在B輸入框中
export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.txt = {
      curren: null,
    };
  }
  // 當(dāng)A組件失焦后觸發(fā)
  blur_handler = () => {
    setTimeout(() => {
      // 獲取當(dāng)前選中的元素
      const focus = document.activeElement;
      // 判斷當(dāng)前選中元素是否為B輸入框
      if (focus === this.txt) {
        console.log("當(dāng)前焦點(diǎn)聚焦在B輸入框中");
      }else{
        console.log("當(dāng)前焦點(diǎn)聚焦不在B輸入框中");
      }
    });
  };
  getBRef = (el) => {
    this.txt = el;
  };
  render() {
    return (
      <div>
        <input type="text" placeholder="A輸入框" onBlur={this.blur_handler} />
        <input type="text" placeholder="B輸入框" ref={this.getBRef} />
      </div>
    );
  }
}

tips:因?yàn)槲以诠ぷ髦惺褂玫膇nput元素是經(jīng)過第三方庫去處理過的,所以當(dāng)使用ref獲取到該元素時,獲取到的并不是input元素本身,而是將input元素包裹了一層的對象,那么此時可以使用.input的方式去獲取真正的input元素.如果使用以上方法不能獲取到對應(yīng)dom元素的話,不妨像我這樣操作下試試~

原文鏈接:https://blog.csdn.net/huanan__/article/details/126950725

欄目分類
最近更新