私のDOMは複雑で、動的な無限スクロールページがあるため、これらのソリューションはどれもうまくいきませんでした。
背景:固定ヘッダーと、ユーザーがスクロールするとその下にくっつく要素をさらに下に使用しています。この要素には検索入力フィールドがあります。さらに、前方および後方スクロール中に動的ページを追加しました。
問題: iOS では、ユーザーが固定要素の入力をクリックすると、ブラウザがページの一番上までスクロールしていました。これにより、望ましくない動作が発生しただけでなく、ページの上部に動的ページが追加されました。
予想される解決策:ユーザーがスティッキー要素の入力をクリックしても、iOS ではスクロールしません (まったくありません)。
解決:
/*Returns a function, that, as long as it continues to be invoked, will not
be triggered. The function will be called after it stops being called for
N milliseconds. If `immediate` is passed, trigger the function on the
leading edge, instead of the trailing.*/
function debounce(func, wait, immediate) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
function is_iOS() {
var iDevices = [
'iPad Simulator',
'iPhone Simulator',
'iPod Simulator',
'iPad',
'iPhone',
'iPod'
];
while (iDevices.length) {
if (navigator.platform === iDevices.pop()) { return true; }
}
return false;
}
$(document).on("scrollstop", debounce(function () {
//console.log("Stopped scrolling!");
if (is_iOS()) {
var yScrollPos = $(document).scrollTop();
if (yScrollPos > 200) { //200 here to offset my fixed header (50px) and top banner (150px)
$('#searchBarDiv').css('position', 'absolute');
$('#searchBarDiv').css('top', yScrollPos + 50 + 'px'); //50 for fixed header
}
else {
$('#searchBarDiv').css('position', 'inherit');
}
}
},250,true));
$(document).on("scrollstart", debounce(function () {
//console.log("Started scrolling!");
if (is_iOS()) {
var yScrollPos = $(document).scrollTop();
if (yScrollPos > 200) { //200 here to offset my fixed header (50px) and top banner (150px)
$('#searchBarDiv').css('position', 'fixed');
$('#searchBarDiv').css('width', '100%');
$('#searchBarDiv').css('top', '50px'); //50 for fixed header
}
}
},250,true));
要件: startsroll および stopscroll 関数が機能するには、JQuery モバイルが必要です。
スティッキー要素によって作成されたラグを滑らかにするために、デバウンスが含まれています。
iOS10でテスト済み。