我需要一个功能来启用/禁用视口,方法是单击按钮。
所以我使用网址参数添加&viewport=1
,就像我可以添加/删除meta name="viewport"
并在此之后重新加载页面一样。
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var $viewport = getParameterByName('viewport'),
$url = window.location.href;
function checkViewport($btn){
if($viewport === '1') {
$('head meta[name=viewport]').remove();
// here I need to change or remove the param from URL
// tried with $url=$url.replace - not working :(
} else if (typeof $viewport === 'undefined' || $viewport === null || $viewport === '') {
$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">');
if ($url.indexOf('?') > -1){
$url += '&viewport=1'
} else {
$url += '?viewport=1'
}
}
window.history.replaceState(null, null, $url);
if($btn){
window.location.href = $url;
}
}
有人可以帮助我吗?
感谢。
答案 0 :(得分:1)
这为您提供了您想要的结果:
var $url = "http://example.com?viewport=1";
console.log($url); //http://example.com?viewport=1
$url = $url.replace(/[&?]viewport=1/g, "");
console.log($url); //http://example.com