[英]How to change href and onclick function of a download button based on device width
我想根据设备宽度(移动设备,平板电脑,个人计算机)更改下载链接,我需要什么js来完成此操作?
<a href="url" onclick="function"; class="btn btn-primary js-scroll-trigger download">Download</a>
In this answer you learn that there are many method of obtaining the device width in js. 在这个答案中,您了解到有很多方法可以在js中获取设备宽度。 One of the best them is the one below:
最好的一种是以下一种:
const mq = window.matchMedia( "(min-width: 500px)" );
if (mq.matches) {
// window width is at least 500px
} else {
// window width is less than 500px
}
So you can do something like (resize window to test for small size): 因此,您可以执行以下操作(调整窗口大小以测试是否较小):
var a_element; function changeHref() { const mq = window.matchMedia( "(min-width: 500px)" ); a_element = document.querySelector(".download"); if (mq.matches) a_element.href = "http://www.google.com"; else a_element.href = "http://www.duckgogo.com"; } changeHref(); console.log(a_element.href);
<a href="url" onclick="function"; class="btn btn-primary js-scroll-trigger download">Download</a>
Dont use width in javascript. 不要在JavaScript中使用width。 Have 3 anchor tags, show only 1 at once using media queries width
具有3个定位标记,使用媒体查询宽度一次仅显示1个
<a onclick="function1()"; class="showOnDesktopOnlyUsingMediaQuery">Download Desktop</a>
<a onclick="function2()"; class="showOnTabletOnlyUsingMediaQuery">Download Tablet</a>
<a onclick="function3()"; class="showOnMobileOnlyUsingMediaQuery">Download Mobile</a>
You can accomplish without even using JavaScript. 您甚至不需要使用JavaScript就可以完成任务。 CSS Media Queries are designed exactly for this type of thing.
CSS Media Queries正是为此类型而设计的。 You make 3 separate
<a>
tags, and alternate between display:inline
or display:none
based on the media queries. 您制作3个单独的
<a>
标签,并根据媒体查询在display:inline
或display:none
之间交替。 For example, on a mobile screen, both the desktop and tablet links will be set to display:none
while the mobile link will be set to display:inline
. 例如,在移动屏幕上,桌面和平板电脑链接都将设置为
display:none
而移动链接将设置为display:inline
。
But if you really need to use JS though, you can do something like the following. 但是,如果您确实需要使用JS,则可以执行以下操作。
HTML: HTML:
<a href="#" id="link-change" class="btn btn-primary js-scroll-trigger download">Download</a>
JavaScript: JavaScript:
var link = document.getElementById("link-change");
var mobile = "url-mobile";
var tablet = "url-tablet";
var desktop = "url-desktop";
link.onclick = function(){
if(screen.width < 768){
link.href = mobile;
} else if(screen.width < 1024){
link.href = tablet;
} else {
link.href = desktop;
}
}
You may need to change the breakpoints (1024px, 768px) I just used those off the top of my head for this example. 您可能需要更改断点(1024像素,768像素),在本示例中,我只是使用了断点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.