0

Можно ли это как то упростить:

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;
}
function fixedRec(el) {
    if($(document).scrollTop() >= el.prev().offset().top + el.prev().outerHeight()) {
        if($(document).scrollTop() < el.parent().outerHeight() - ($(window).outerHeight() / 1.5)) {
            if(is_iOS() || $(window).width() < 1000){
                el.removeClass('fixed').addClass('absolute').css({top: (top - 150)});
            } else {      
                el.removeAttr('style').removeClass('absolute').addClass('fixed');
            }
        } else {
            el.removeAttr('style').removeClass('fixed').addClass('absolute');
        }
    } else {
        el.removeAttr('style').removeClass('absolute').removeClass('fixed');
    }
}

2 ответа 2

1

Вместо этой жести

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;
}

Можно сделать.

function checkIOS() {
  var iDevices = ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'];
  
  return iDevices.includes(navigator.platform);
}

console.log(checkIOS());

Есть еще способ с .test(), но у вас уже есть массив.
Вы уверены, что там должно быть "ИЛИ" в проверке на устройства и размер окна?

1
  • Array.prototype.includes отсутствует в IE/Edge. Я бы использовал some.
    – user236014
    3 фев 2017 в 13:24
0

is_iOS переписываем используя Array.prototype.some

function is_iOS() {
    var iDevices = ['iPad Simulator', 'iPhone Simulator', 'iPod Simulator', 'iPad', 'iPhone', 'iPod'];
    return iDevices.some(dev => dec === navigator.platform);
}

fixedRec делаем чуть менее выпуклым, за счёт замены else на return.
Обязательно добавляем комментарии, что происходит в каждом конкретном случае. Например: Долистали до следующего элемента.

function fixedRec(el) {
  let top = $(document).scrollTop();

  if (top < el.prev().offset().top + el.prev().outerHeight()) {
    // comment
    el.removeAttr('style').removeClass('absolute').removeClass('fixed');
    return;
  }
  if (top >= el.parent().outerHeight() - ($(window).outerHeight() / 1.5)) {
    // comment
    el.removeAttr('style').removeClass('fixed').addClass('absolute');
    return;
  }
  if(is_iOS() || $(window).width() < 1000){
    el.removeClass('fixed').addClass('absolute').css({top: (top - 150)});
  } else {      
    el.removeAttr('style').removeClass('absolute').addClass('fixed');
  }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.