如何根据使用的设备更改href

问题描述 投票:-2回答:1

我正在尝试根据用户使用的设备获得不同的下载。例如,如果用户使用PC有X下载链接。如果用户使用的是iPhone,iPod或iPad,请使用Y链接。我不是试图使用设备像素宽度我试图使用一些东西来检测用户代理。 (注意:我只为iOS用户制作不同的链接)

我尝试了以下但是当我点击下载时它使用我的网站名称然后/ url ex:examplewebsite.com/url

var a_element;

function changeHref() {
  a_element = document.querySelector(".download");
  if ((navigator.platform.match(/i(Phone|Pod))/i)) || (navigator.userAgent.match(/iPad/i))) {
    a_element.href = "mobile download";
  } else {
    a_element.href = "pc download";
  }
}
changeHref();
<a href="url" onclick="function" ; class="btn btn-primary js-scroll-trigger download">Download</a>
javascript html
1个回答
0
投票

const getHref = () => {
  const element = document.getElementById("myLink");
  const IS_IPAD = navigator.userAgent.match(/iPad/i) != null;
  const IS_IPHONE = (navigator.userAgent.match(/iPhone/i) != null) || (navigator.userAgent.match(/iPod/i) != null);
  
  if (IS_IPAD || IS_IPHONE) {
    element.href = "iphone/ipad/url"; // when the device is an iphone/ipad
  } else {
    element.href = "whatever/url"; // default
  };
};

getHref();
<a id="myLink" >My Link</a>
© www.soinside.com 2019 - 2024. All rights reserved.