[英]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.innerWidth
或window.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.