Отключение позиции: исправлено при прокрутке, когда 250 пикселей от нижней части страницы

$(window).scroll(function() {
  $(".lay-fixed").css("bottom", Math.max(0, 250 - $(this).scrollBottom()));
});
.lay-fixed {
  position: fixed;
  right: 30px
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "col-md-6 lay-fixed" id = "gotobooking">
  ----widget code-----
</div>

Здесь я пытаюсь отключить элемент position:fixed при прокрутке на расстоянии 250 пикселей от нижней части страницы. Помогите мне найти способ исправить это.

Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
0
59
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Пожалуйста, попробуйте:

$.fn.followTo = function (pos) {
    var $this = this,
        $window = $(window);

    $window.scroll(function (e) {
        if ($window.scrollTop() > pos) {
            $this.css({
                position: 'absolute',
                top: pos
            });
        } else {
            $this.css({
                position: 'fixed',
                top: 0
            });
        }
    });
};

$('.lay-fixed').followTo(250);
.lay-fixed {
  position: fixed;
  right: 30px
}
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "col-md-6 lay-fixed" id = "gotobooking">
     ----widget code-----

</div>
<div>
  But I must explain to you how all<br /> this mistaken idea of denouncing pleasure and praising<br /> pain was born and I will give you a complete account of the<br /> system, and expound the actual teachings of the great<br /> explorer of the truth, the master-builder of human happiness.<br /> No one rejects, dislikes, or avoids pleasure itself, because<br /> it is pleasure, but because those who do not know how<br /> to pursue pleasure rationally encounter consequences<br /> that are extremely painful. Nor again is there anyone<br /> who loves or pursues or desires to obtain pain of itself,<br /> because it is pain, but because occasionally circumstances<br /> occur in which toil and pain can procure him some great pleasure.<br /> To take a trivial example, which of us ever undertakes<br /> laborious physical exercise, except to obtain some<br /> advantage from it? But who has any right to find fault with<br /> a man who chooses to enjoy a pleasure that has no annoying<br /> consequ
  But I must explain to you how<br /> all this mistaken idea of denouncing pleasure and praising pain<br /> was born and I will give you a complete account of the system,<br /> and expound the actual teachings of the great explorer of<br /> the truth, the master-builder of human happiness. No one rejects,<br /> dislikes, or avoids pleasure itself, because it is pleasure,<br /> but because those who do not know how to pursue<br /> pleasure rationally encounter consequences that are<br /> extremely painful. Nor again is there anyone who loves<br /> or pursues or desires to obtain pain of itself, because it is pain,<br /> but because occasionally circumstances<br /> occur in which toil and pain can procure him some great pleasure.<br /> To take a trivial example, which of us ever undertakes<br /> laborious physical exercise, except to obtain some advantage<br /> from it? But who has any right to find fault with a man who<br /> chooses to enjoy a pleasure that has no annoying consequ<br />
  But I must explain to you how all<br /> this mistaken idea of denouncing pleasure and praising pain<br /> was born and I will give you a complete account of the system,<br /> and expound the actual teachings of the great explorer of<br /> the truth, the master-builder of human happiness. No one rejects,<br /> dislikes, or avoids pleasure itself, because it is pleasure,<br /> but because those who do not know how to pursue<br /> pleasure rationally encounter consequences that are<br /> extremely painful. Nor again is there anyone who loves<br /> or pursues or desires to obtain pain of itself, because<br /> it is pain, but because occasionally circumstances occur<br /> in which toil and pain can procure him some great pleasure.<br /> To take a trivial example, which of us ever undertakes laborious<br /> physical exercise, except to obtain some advantage from it?<br /> But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequ
</div>

Как добавить в этот блок медиа-запрос, который выполняется только при ширине экрана больше 767?

Ponnaveen S 09.04.2019 10:55

Например: @media (min-width: 768px) { .lay-fixed { Ваш код... } }

Joykal Infotech 09.04.2019 11:40

Приведенный выше ответ отлично подходит для вас, тогда, пожалуйста, примите и поддержите ответ.

Joykal Infotech 09.04.2019 11:42

Другие вопросы по теме