如何让我的脚本只在移动设备上激活?

How can I have my script only activated on mobile devices?

我有一个搜索,我想将其跳到顶部,但只针对移动用户。

如何自己设置宽度?

到目前为止,这是我的代码:

$('input, textarea').focus(function () {
    $('html, body').animate({ scrollTop: ($('input, textarea').offset().top - 10) }, 1);
    return false;
});

您可以使用:

let isMobile = false;

if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    isMobile = true;
}

$('input, textarea').focus(function () {
    if (isMobile) {
        $('html, body').animate({ scrollTop: ($('input, textarea').offset().top - 10) }, 1);
        return false;
    }
});

您可以使用 matchMedia 方法:

https://caniuse.com/matchmedia

https://www.w3schools.com/jsref/met_win_matchmedia.asp

$('input, textarea').focus(function() {
  if (window.matchMedia("(max-width: 700px)").matches) {
    $('html, body').animate({
      scrollTop: ($('input, textarea').offset().top - 10)
    }, 800);
  }
});

https://jsfiddle.net/ju6k3grm/2/