简体   繁体   English

根据视口大小更改href(无jquery)

[英]Change href depending on viewport size (without jquery)

I want to be able to change a href depending upon window width: on initial page load and window resize (without jquery or other external libraries). 我希望能够根据窗口宽度来更改href:在初始页面加载和窗口调整大小时(无需jquery或其他外部库)。 Thank you! 谢谢!

Here is an experiment using an answer to a similar question: doesn't seem to be working for me. 这是一个使用类似问题答案的实验:似乎不适用于我。 https://codepen.io/marcusdeacey/pen/wLLNXb https://codepen.io/marcusdeacey/pen/wLLNXb

HTML 的HTML

<a id="myLink" href="http://highresolutionurl">My Link</a>

JS JS

if (screen.width < 768) {
    document.getElementById('myLink').setAttribute('href', "http://highresolutionurl");
}
else if {
    document.getElementById('myLink').setAttribute('href', "http://lowresolutionurl");
}

There's a JavaScript variable called screen.width which is pretty self explanatory, it gets the screens width. 有一个名为screen.width的JavaScript变量,它很容易说明,它获取屏幕的宽度。 So for example: 因此,例如:

if (screen.height > screen.width) {
  //This means your on a mobile device so if you wanted people on mobile to go to mobile support instead of desktop support you could use this method
}
else {
  //do something
}
//or you could just
if (screen.width == 1360) {
  //Do this for people with only 1360 pixel wide screens
}
else {
  //Do this for people without 1360 pixel screens
}

screen.width doesn't change unless you change the display settings on your computer or mobile device. 除非您更改计算机或移动设备上的显示设置,否则screen.width不会更改。 If you want this link to change dynamically with the width of the window , you need either window.innerWidth or window.outerWidth . 如果希望此链接随窗口的宽度动态变化,则需要window.innerWidthwindow.outerWidth

If you want this to change dynamically, you can't just do it once, you need to monitor changes in window size. 如果要动态更改,则不能只执行一次,而是需要监视窗口大小的更改。

var myLink = document.getElementById('myLink');

function setLink() {
  if (window.innerWidth < 768) {
    myLink.setAttribute('href', "http://highresolutionurl");
  }
  else {
    myLink.setAttribute('href', "http://lowresolutionurl");
  }
}

setLink();

window.addEventListener('resize', setLink);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM