仅用于输入类型文本或TEL的焦点,而不是无线电或复选框



我正在使用此代码自动滚动到选定的输入类型:

$( document ).on( "focus", "input", function() {
            if(document.activeElement.tagName=="INPUT"){
                     window.setTimeout(function(){
                        document.activeElement.scrollIntoView();
                     },0);
                  }
            return false;
});

问题是,我想排除无线电按钮和复选框..仅将其用于输入类型teltext。我该如何实现?

您只能根据其类型选择相关输入,而不是选择所有输入标签:

$( document ).on( "focus", "input[type='tel'],input[type='text']", function() {
  console.log('relevant element focused');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" value="1" />
<input type="text" value="this is some text" />
<input type="tel" value="123456789" />
<input type="checkbox" value="123456789" />

另一个选项是检查聚焦元素的type,并在选定类型的情况下打破功能的运行:

$( document ).on( "focus", "input", function() {
  if ($(this).attr('type') == 'radio' || $(this).attr('type') == 'checkbox') {
    return;
  }
  console.log('relevant element focused');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" value="1" />
<input type="text" value="this is some text" />
<input type="tel" value="123456789" />
<input type="checkbox" value="123456789" />

最新更新