簡體   English   中英

根據視口大小更改href(無jquery)

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

我希望能夠根據窗口寬度來更改href:在初始頁面加載和窗口調整大小時(無需jquery或其他外部庫)。 謝謝!

這是一個使用類似問題答案的實驗:似乎不適用於我。 https://codepen.io/marcusdeacey/pen/wLLNXb

的HTML

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

JS

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

有一個名為screen.width的JavaScript變量,它很容易說明,它獲取屏幕的寬度。 因此,例如:

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不會更改。 如果希望此鏈接隨窗口的寬度動態變化,則需要window.innerWidthwindow.outerWidth

如果要動態更改,則不能只執行一次,而是需要監視窗口大小的更改。

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