有兩個解決辦法:函數
一、返回到指定的頁面 this
1
2
3
4
5
6
7
8
9
10
11
|
pushHistory();
window.addEventListener(
"popstate"
,
function
(e) {
},
false
);
function
pushHistory() {
var
state = {
title:
"title"
,
url:
"#"
};
window.history.pushState(state,
"title"
,
"#"
);
}
|
二、js文件方法url
此聲明函數在xback.js文件裏有,在app.js裏必須再聲明一次,否則監聽返回事件失敗。spa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
/**
* 使用 HTML5 的 History 新 API pushState 來曲線監聽 Android 設備的返回按鈕
* XBack.listen(function(){
alert('oh! you press the back button');
});
*/
;!
function
(pkg, undefined){
var
STATE =
'x-back'
;
var
element;
var
onPopState =
function
(event){
event.state === STATE && fire();
}
var
record =
function
(state){
history.pushState(state,
null
, location.href);
}
var
fire =
function
(){
var
event = document.createEvent(
'Events'
);
event.initEvent(STATE,
false
,
false
);
element.dispatchEvent(event);
}
var
listen =
function
(listener){
element.addEventListener(STATE, listener,
false
);
}
;!
function
(){
element = document.createElement(
'span'
);
window.addEventListener(
'popstate'
, onPopState);
this
.listen = listen;
record(STATE);
}.call(window[pkg] = window[pkg] || {});
}(
'XBack'
);
|
調用方法:code
1
2
3
|
XBack.listen(
function
(){
alert(
'back'
);
});
|
總結事件
以上所述是小編給你們介紹的JavaScript監聽手機物理返回鍵的兩種解決方法ip